Last active
February 8, 2019 19:55
-
-
Save flucivja/36a324f183c212d0e1cf449631e725a3 to your computer and use it in GitHub Desktop.
React hooks testing act warning
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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