When testing, code that causes React state updates should be wrapped into act - reactjs

I have this test:
import {
render,
cleanup,
waitForElement
} from '#testing-library/react'
const TestApp = () => {
const { loading, data, error } = useFetch<Person>('https://example.com', { onMount: true });
return (
<>
{loading && <div data-testid="loading">loading...</div>}
{error && <div data-testid="error">{error.message}</div>}
{data &&
<div>
<div data-testid="person-name">{data.name}</div>
<div data-testid="person-age">{data.age}</div>
</div>
}
</>
);
};
describe("useFetch", () => {
const renderComponent = () => render(<TestApp/>);
it('should be initially loading', () => {
const { getByTestId } = renderComponent();
expect(getByTestId('loading')).toBeDefined();
})
});
The test passes but I get the following warning:
Warning: An update to TestApp inside a test was not wrapped in
act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser
in TestApp
console.error
node_modules/react-dom/cjs/react-dom.development.js:506
Warning: An update to TestApp inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser
in TestApp

The key is to await act and then use async arrow function.
await act( async () => render(<TestApp/>));
Source:
https://stackoverflow.com/a/59839513/3850405

Try asserting inside 'await waitFor()' - for this your it() function should be async
it('should be initially loading', async () => {
const { getByTestId } = renderComponent();
await waitFor(() => {
expect(getByTestId('loading')).toBeDefined();
});
});
Keep calm and happy coding

I was getting the same issue which gets resolved by using async queries (findBy*) instead of getBy* or queryBy*.
expect(await screen.findByText(/textonscreen/i)).toBeInTheDocument();
Async query returns a Promise instead of element, which resolves when an element is found which matches the given query. The promise is rejected if no element is found or if more than one element is found after a default timeout of 1000ms. If you need to find more than one element, use findAllBy.
https://testing-library.com/docs/dom-testing-library/api-async/
But as you know it wont work properly if something is not on screen. So for queryBy* one might need to update test case accordingly
[Note: Here there is no user event just simple render so findBy will work otherwise we need to put user Event in act ]

Try using await inside act
import { act } from 'react-dom/test-utils';
await act(async () => {
wrapper = mount(Commponent);
wrapper.find('button').simulate('click');
});

test('handles server ok', async () => {
render(
<MemoryRouter>
<Login />
</MemoryRouter>
)
await waitFor(() => fireEvent.click(screen.getByRole('register')))
let domInfo
await waitFor(() => (domInfo = screen.getByRole('infoOk')))
// expect(domInfo).toHaveTextContent('登陆成功')
})
I solved the problem in this way,you can try it.

I don't see the stack of the act error, but I guess, it is triggered by the end of the loading when this causes to change the TestApp state to change and rerender after the test finished. So waiting for the loading to disappear at the end of the test should solve this issue.
describe("useFetch", () => {
const renderComponent = () => render(<TestApp/>);
it('should be initially loading', async () => {
const { getByTestId } = renderComponent();
expect(getByTestId('loading')).toBeDefined();
await waitForElementToBeRemoved(() => queryByTestId('loading'));
});
});

React app with react testing library:
I tried a lot of things, what worked for me was to wait for something after the fireevent so that nothing happens after the test is finished.
In my case it was a calendar that opened when the input field got focus. I fireed the focus event and checked that the resulting focus event occured and finished the test. I think maybe that the calendar opened after my test was finished but before the system was done, and that triggered the warning. Waiting for the calendar to show before finishing did the trick.
fireEvent.focus(inputElement);
await waitFor(async () => {
expect(await screen.findByText('December 2022')).not.toBeNull();
});
expect(onFocusJestFunction).toHaveBeenCalledTimes(1);
// End
Hopes this helps someone, I just spent half a day on this.

This is just a warning in react-testing-library (RTL). you do not have to use act in RTL because it is already using it behind the scenes. If you are not using RTL, you have to use act
import {act} from "react-dom/test-utils"
test('',{
act(()=>{
render(<TestApp/>)
})
})
You will see that warning when your component does data fetching. Because data fetching is async, when you render the component inside act(), behing the scene all the data fetching and state update will be completed first and then act() will finish. So you will be rendering the component, with the latest state update
Easiest way to get rid of this warning in RTL, you should run async query functions findBy*
test("test", async () => {
render(
<MemoryRouter>
<TestApp />
</MemoryRouter>
);
await screen.findByRole("button");
});

Related

How do I test a React Native Context that has an a sync call in useEffect

There are other questions similar but this is specific to React Native and I have a React Context which has a provider and the provider has a useEffect hook that calls an async function that would update the state.
The actual async operation I have mocked to return a resolved promise.
Initially I did this to make sure the initial states are okay
const { getByTestId} = render(<FontProvider><My Component /></FontProvider>);
expect(getByTestId(...
The default state works as expected but when I want the next state after the useEffect it does not work. Obviously because I didn't wrap in act.
However, I am unable to wrap around act since it is a render call. At least not in #testing-library/react-native as it shows
Can't access .root on unmounted test renderer
Is there something else I may be missing?
I'm not using setTimeout so jest.runAllTimers(); doesn't make sense.
I was close with the jest.runAllTimers(). There's another method jest.runAllTicks() but still requires fake timers.
beforeEach(() => { jest.useFakeTimers(); });
it("...", () => {
...
const { getByTestId } =
render((<FontsProvider fontModules={[mockFont]}>
<MyComponent /></FontsProvider>);
// runs the useEffects no need for async/await
act(() => { jest.runAllTicks() })
expect(getByTestId("blah").props.style).toStrictEqual(
{ fontFamily: "IBMPlexSans_300Light" });
);
afterEach(() => { jest.useRealTimers(); });

Is it necessary to call unmount after each test cases in react testing libarary?

describe('<CustomTooltip />', () => {
it('should show tooltip text', async () => {
const { container, unmount } = render(<CustomTooltip text='Tooltip Text' />)
userEvent.hover(container.querySelector('svg'))
await screen.findByText('Tooltip Text')
screen.debug()
unmount() // ?? is it necessary to call unmount after each test cases?
})
it('check if there is an mounted component', () => {
screen.debug()
})
})
Is it necessary to call unmount after each test cases? Because I've added useEffect in the CustomTooltip component, and Unmounted is logged before the second test case. And even the second test case screen.debug output is <body />.
useEffect(() => {
console.log('Mounted')
return () => console.log('Unmounted')
}, [])
I asked this because i saw a custom implementation for render in test utils to unmount component after each test cases, and I'm curious to know if this is really important.
let lastMount = null;
const _render = (...args) => {
lastMount = render(...args);
return lastMount;
};
afterEach(() => {
if (lastMount)
lastMount.unmount();
lastMount = null;
});
It depends on the testing framework that you are using. If you are using jest, for instance, it's not needed.
Here is a reference to this suggestion https://kentcdodds.com/blog/common-mistakes-with-react-testing-library#using-cleanup
For a long time now cleanup happens automatically (supported for most major testing frameworks) and you no longer need to worry about it

Make Unit Test Wait for Data filled by Asynchronous Fetch

I have a unit test which includes rendering a component that uses useSWR to fetch data. But the data is not ready before the expect() is being called so the test fails.
test("StyleOptionDetails contains correct style option number", () => {
renderWithMockSwr(
<StyleOptionDetails
{...mockIStyleOptionDetailsProps}
/>
)
expect(screen.getByText(123)).toBeInTheDocument();
});
But if I put in a delay setTimeout(), it will pass the test.
setTimeout(() => {
console.log('This will run after 2 second')
expect(screen.getByText(123)).toBeInTheDocument();
}, 2000);
What is the correct way to create a delay or wait for the data?
Although I think you are already doing this, the first thing to note is that you shouldn't be actually fetching any data from your tests-- you should be mocking the result.
Once you are doing that, you will use the waitFor utility to aid in your async testing-- this utility basically accepts a function that returns an expectation (expect), and will hold at that point of the test until the expectation is met.
Let's provide an example. Take the imaginary component I've created below:
const MyComponent = () => {
const [data, setData] = useState();
useEffect(() => {
MyService.fetchData().then((response) => setData(response));
}, []);
if (!data) {
return (<p>Loading...</p>);
}
// else
return (
<div>
<h1>DATA!</h1>
<div>
{data.map((datum) => (<p>{datum}</p>))}
</div>
</div>
);
}
So for your test, you would do
import MyService from './MyService';
import MyComponent from './MyComponent';
describe('MyComponent', () => {
const mockData = ['Spengler', 'Stanz', 'Venkman', 'Zeddmore'];
beforeEach(() => {
jest.spyOn(MyService, 'fetchData')
.mockImplementation(
() => new Promise((res) => setTimeout(() => res(mockData), 200))
);
});
afterEach(() => {
MyService.fetchData.mockRestore();
});
it('displays the loading first and the data once fetched', async () => {
render(<MyComponent />);
// before fetch completes
expect(screen.getByText(/Loading/)).toBeInTheDocument();
expect(screen.queryByText('DATA!')).toBeNull();
// after fetch completes..
// await waitFor will wait here for this to be true; if it doesn't happen after about five seconds the test fails
await waitFor(() => expect(screen.getByText('DATA!')).toBeInTheDocument());
expect(screen.queryByText(/Loading/)).toBeNull(); // we don't have to await this one because we awaited the proper condition in the previous line
});
});
This isn't tested but something like this should work. Your approach to mocking may vary a bit on account of however you've structured your fetch.
I have a similar answer elsewhere for a ReactJS question, Web Fetch API (waiting the fetch to complete and then executed the next instruction). Let me thresh out my solution for your problem.
If your function renderWithMockSwr() is asynchronous, then if you want it to wait to finish executing before calling the next line, use the await command.
await renderWithMockSwr(
<StyleOptionDetails
{...mockIStyleOptionDetailsProps}
/>
)
async is wonderful. So is await. Check it out: Mozilla Developer Network: Async Function

Test multiple React component state changes using Test Renderer

The component that I am trying to test is having state isSubmitting which is set true when we try to submit the form and then it is set back to false when we receive the response from server.
I want to test the state of component after each state update.
const Component = () => {
const [isSubmitting, setIsSubmitting] = useState();
const handlePress = async () => {
setIsSubmitting(true);
await submitForm();
setIsSubmitting(false);
};
return (
<>
<button onPress={() => this.handlePress} />
{isSubmitting && <IsSubmitting />}
</>
)
}
I am able to test only the first component state eg. when I update isSubmitting to true.
import React from 'react';
import { act, create } from 'react-test-renderer';
import Component from './Component';
it('shows loading screen after submit, and hides it after', async () => {
jest.spyOn(form, 'submitForm').mockResolvedValue();
const wrapper = create(<Component />);
act(() => {
wrapper.root.findByType(Button).props.onPress();
});
expect(wrapper.root.findByType(IsSubmitting)).toBeDefined();
});
How can I check that the IsSubmitting component is hidden afterwards? I am also getting an error for not wrapping update into act().
console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:104
Warning: An update to Component inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/docs/test-utils.html#act
in Component
I had to call act function twice. For the first time without await and for the second time with async await.
const wrapper = create(<Component />);
act(() => {
wrapper.root. findByType(Button).props.onPress();
});
expect(wrapper.root.findByType(IsSubmitting)).toBeDefined();
await act(async () => {});
expect(wrapper.root.findAllByType(IsSubmitting)).toStrictEqual([]);'
This way, I am able to test component in both states.

Why does react hook throw the act error when used with fetch api?

I keep getting Warning: An update to App inside a test was not wrapped in act(...). in my test suite whenever I make an API request and update the state.
I'm making use of react-testing-library. I also tried using ReactDOM test utils, got the same result. One other thing I tried was wrapping the container in act, still got the same result.
Please note that: My App works and my test passes. I just need to know what I was doing wrong or if it's a bug in the react-dom package that's making that error show up. And it's bad to mock the console error and mute it.
global.fetch = require('jest-fetch-mock');
it('should clear select content item', async () => {
fetch.mockResponseOnce(JSON.stringify({ results: data }));
const { container } = render(<App />);
const content = container.querySelector('.content');
await wait();
expect(content.querySelectorAll('.content--item').length).toBe(2);
});
Here's the hook implementation:
const [data, setData] = useState([]);
const [error, setError] = useState('');
const fetchInitData = async () => {
try {
const res = await fetch(API_URL);
const data = await res.json();
if (data.fault) {
setError('Rate limit Exceeded');
} else {
setData(data.results);
}
} catch(e) {
setError(e.message);
}
};
useEffect(() => {
fetchInitData();
}, [isEqual(data)]);
It's a known problem, check this issue in Github https://github.com/kentcdodds/react-testing-library/issues/281
For anyone who stumbles upon this more than a year later as I did, the issue Giorgio mentions has since been resolved, and wait has since been replaced with waitFor, as documented here:
https://testing-library.com/docs/dom-testing-library/api-async/
That being the case, I believe the solution to the warning now should be something like this:
import { render, waitFor } from '#testing-library/react';
// ...
it('should clear select content item', async () => {
fetch.mockResponseOnce(JSON.stringify({ results: data }));
const { container } = render(<App />);
const content = container.querySelector('.content');
await waitFor(() =>
expect(content.querySelectorAll('.content--item').length).toBe(2);
);
});
In my case, I had an App component loading data asynchronously in a useEffect hook, and so I was getting this warning on every single test, using beforeEach to render App. This was the specific solution for my case:
beforeEach(async () => {
await waitFor(() => render(<App />));
});
To get rid of the act() warning you need to make sure your promises resolve synchronously. You can read here how to do this.
Summary:
The solution for this is a bit involved:
we polyfill Promise globally with an implementation that can resolve
promises 'immediately', such as promise
transpile your javascript with a custom babel setup like the one in this repo
use jest.runAllTimers(); this will also now flush the promise task queue
I had this problem and gave up using wait and async instead used jest faketimers and so on, so your code should be something like this.
global.fetch = require('jest-fetch-mock');
it('should clear select content item', /*async */ () => {
jest.useFakeTimers();
fetch.mockResponseOnce(JSON.stringify({ results: data }));
const { container } = render(<App />);
const content = container.querySelector('.content');
// await wait();
act(() => {
jest.runAllTimers();
});
expect(content.querySelectorAll('.content--item').length).toBe(2);
});

Resources