React Testing Librbary & Jest part 7 The Mysterious 'Act' Function!
===

---
###### tags: `React Testing Library`, `Jest`, `React`
## Unexpected State Updates
`act()` Warnings: Will occur fequently if you're doing data fetching in `useEffect`.
## Important concepts
1. Unexpected state updates in tests are bad.
2. The act function defines a window in time where state updates can (and should) occur.
3. React Testing library uses `act` behind the scenes.
4. To solve act warnings, you should use a `findBy`. **Usually** you don't want to follw the advice of the warning.
---
### 📌Unexpected state updates in tests are bad
For example: User Clicks button to load some data.
```javascript
const UserLists () => {
const [isLoaded, setIsLoaded] = useState(false);
const [users, setUsers] = useState([]);
useEffect(() => {
if(isLoaded) fetchUsers().then(data => setUsers(data))
}, [isLoaded]);
return <button onClick={() => setLoaded(true)}> Load </button>
}
```
Here's the test.
```javascript
text('clicking button to load user', () => {
render(<UserLists/>);
const button = screen.getByRole('button');
user.click(button);
const users = screen.getByAllRole('listitem');
expect(users).toHaveLenghth(3);
})
```

Because we did not wait until the request has resolved, therefore our test fails.
---
### 📌 The act function defines a window in time where state updates can (and should) occur.
Test without RTl
```javascript
import { render } from 'react-dom';
import { act } from 'react-dom/test-utils';
test('clicking the button loads users', () => {
act(() => {
render(<UserLists/>)
});
const button = document.querySelector('button');
await act(async() => {
button.dispatch(new MouseEvent('click'));
});
const users = document.querySelectorAll('li')
expect(users).toHaveLength(3);
})
```


---
### 📌 React Testing library uses `act` behind the scenes.

---
### 📌 To solve act warnings, you should use a `findBy`. **Usually** you don't want to follw the advice of the warning.

1. Do not add an `act` to test.
2. Use one of RTL's function instead.
---
## Solve `act` warning
Let's fix `arc` warning by implementing sevreal solutions from best to worst.

### ✒️ Using `findBy` or `findAllBy`
#### ✅ Analize the cause of error.
Look at the first line of the erro, we can understand that `FileIcon` was the reason causing the error, let's check inside our app.

It looked like it had some sort of promise inside of `useEffect`

#### ✅ Check when did the FileIcon show up.
We can make our test waiting for a sec and using `debug()` to check component.
```javascript
test('shows a link icon to the github homepage for the repo', async () => {
renderComponent();
// This would show the difference before and after implementing pause function.
screen.debug();
await pause();
screen.debug();
});
const pause = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 100);
});
};
```
We can see that after `await pause()`, from the component there's `<i>` which represented the `FileIcon`.

#### ✅ Clean debug code and find the role we need.
```javascript
test('shows a link icon to the github homepage for the repo', async () => {
renderComponent();
await screen.findByRole('img');
});
```
When save the file, we still can see the warning, that's because there're two `img` as roles in the component.

#### ✅ Be more specific about the role we want to target.
```javascript
test('shows a link icon to the github homepage for the repo', async () => {
renderComponent();
await screen.findByRole('img', { name: /javascript/i });
const link = screen.getByRole('link');
expect(link).toHaveArrtibute('href', '/repositories/facebook/react');
});
```
#### ✅ Warning is gone!

---
### ✒️ Using an module mock
In this test, our goal is to find the link, the warning was caused by `FileIcon` which was something we can ignore, using module mock to help us ignoring render `FileIcon`.
```javascript
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import RepositoriesListItem from './RepositoriesListItem';
jest.mock('../tree/FileIcon', () => {
return () => {
return 'FileIcon component';
};
});
const renderComponent = () => {
const repository = {
full_name: 'facebook/react',
language: 'Javascript',
description: 'A js library',
owner: 'facebook',
name: 'react',
html_url: 'https://www.github.com/facebook/react',
};
render(
<MemoryRouter>
<RepositoriesListItem repository={repository} />
</MemoryRouter>
);
};
test('shows a link icon to the github homepage for the repo', async () => {
renderComponent();
});
```
Here we use `jest.mock()` to kind of "render" `FileIcon` as string, instead of real component, using this approach requires to have a good understanding of the test case, if the result of getting `FileIcon` is not important here, then we can skip it.
---
### ✒️ Using an act to control (NOT RECOMMEND)
```javascript
test('shows a link icon to the github homepage for the repo', async () => {
renderComponent();
await act(async () => {
await pause();
});
});
const pause = () => new Promise((resolve) => setTimeout(resolve, 100));
```
---
### ✅Optimize!
Here we don't want to copy `html_url` everytime because someone might change the url in the future, therefore, we can return `repository` and destructur it and access in the assertion.
```javascript
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import RepositoriesListItem from './RepositoriesListItem';
const renderComponent = () => {
const repository = {
full_name: 'facebook/react',
language: 'Javascript',
description: 'A js library',
owner: 'facebook',
name: 'react',
html_url: 'https://github.com/facebook/react',
};
render(
<MemoryRouter>
<RepositoriesListItem repository={repository} />
</MemoryRouter>
);
return { repository };
};
test('shows a link icon to the github homepage for the repo', async () => {
const { repository } = renderComponent();
await screen.findByRole('img', { name: /javascript/i });
const link = screen.getByRole('link');
expect(link).toHaveAttribute('href', repository.html_url);
});
```
The test above was failed, because of this.

Let's dig more, take look at the component, here the component is already shown link and it will generate an anchor element, we were finding the incorrect element inside of the component.

In order to fix it, we need to be more specific with the selector, first let's add one more link to the component and give an `arai-label`.

```javascript!
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import RepositoriesListItem from './RepositoriesListItem';
const renderComponent = () => {
const repository = {
full_name: 'facebook/react',
language: 'Javascript',
description: 'A js library',
owner: 'facebook',
name: 'react',
html_url: 'https://github.com/facebook/react',
};
render(
<MemoryRouter>
<RepositoriesListItem repository={repository} />
</MemoryRouter>
);
return { repository };
};
test('shows a link icon to the github homepage for the repo', async () => {
const { repository } = renderComponent();
await screen.findByRole('img', { name: /javascript/i });
const link = screen.getByRole('link', { name: /github repository/i });
expect(link).toHaveAttribute('href', repository.html_url);
});
```