Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React hooks testing act warning
// this is simplified example of testing react hook where I am getting warning that test code should be wrapped in act.
function usePromise(promise) {
const [data, setData] = useState({
isLoading: true,
data: null
});
useEffect(() => {
promise.then((res) => {
setData({
isLoading: false,
data: res
});
}, () => {
setData({
isLoading: false,
data: null
});
});
});
return data;
}
function TestComponent({promise}) {
const data = usePromise(promise);
return <div>{JSON.stringify(data)}</div>;
}
it('warns that I should use wrap code in act', async () => {
const deferred = new Deferred(); // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred#Backwards_and_forwards_compatible_helper
const wrapper = mount(<TestComponent promise={deferred.promise} />); // using enzyme mount
expect(wrapper.text()).toEqual('{"isLoading":true,"data":null}');
act(() => deferred.resolve('test')); // if this would not be in act test would fail
await deferred.promise;
expect(wrapper.text()).toEqual('{"isLoading":false,"data":"test"}');
});
/*
Test pass but I get warning:
Warning: An update to TestComponent inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.