Comments (14)
For anyone else stumbling across this issue: https://testing-library.com/docs/dom-testing-library/api-async/#waitfor
from react-hooks-testing-library.
So using useFetch
as an example, I came up with:
import fetch from 'node-fetch'
import { useFetch } from 'react-async'
import { renderHook, cleanup } from 'react-hooks-testing-library'
window.fetch = fetch
describe('useFetch tests', () => {
afterEach(cleanup)
test('should use fetch', (done) => {
const { result, rerender } = renderHook(() =>
useFetch(
'https://swapi.co/api/people/1',
{ Accept: 'application/json' },
{
onResolve: () => {
rerender()
expect(result.current.isLoading).toBe(false)
done()
},
onReject: () => {
done.fail(new Error('request failed'))
}
}
)
)
expect(result.current.isLoading).toBe(true)
})
})
This test passes, however, the "not wrapped in act
" warning is displayed:
PASS test/useFetch.test.js
● Console
console.error node_modules/react-dom/cjs/react-dom.development.js:506
Warning: An update to TestHook 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://fb.me/react-wrap-tests-with-act
in TestHook
I believe I have tracked the warning down to the setState
that eventually gets called when the promise resolves.
To be honest, I'm not sure how we are supposed to wrap the promise resolution in an act
call. I tried a few of the suggestions in @threepointone's examples, but could not prevent the message from showing, even using fetch-mock
to mock the API. Perhaps a different API on the hook would allow some of them to work, but I'm not sure.
from react-hooks-testing-library.
For anyone else stumbling across this issue: https://testing-library.com/docs/dom-testing-library/api-async/#waitfor
This solved my issue (mind that this is a custom implementation of useFetch):
import "@testing-library/jest-dom"
import { renderHook, waitFor } from "@testing-library/react"
import { rest } from "msw"
import { setupServer } from "msw/node"
import useFetch from "./useFetch"
const pokemonEndpoint = jest.fn()
const handlers = [
rest.get("https://pokeapi.co/api/v2/pokemon", pokemonEndpoint)
]
const server = setupServer(...handlers)
describe("The useFetch hook", () => {
beforeAll(() => server.listen())
afterAll(() => server.close())
it("automatically fetches the given URL when called", async () => {
const { result } = renderHook(() => useFetch("https://pokeapi.co/api/v2/pokemon"))
await waitFor(() => expect(result.current.status).toBe("fetching"))
expect(pokemonEndpoint).toHaveBeenCalled()
})
})
from react-hooks-testing-library.
I'm also in favour of Promise
over callbacks... if nothing else, it removes the ambiguity if the value changes twice.
Ok, let's see if we cant get something like this working
test('should use fetch', async () => {
const { result } = renderHook(() =>
useFetch('https://swapi.co/api/people/1', { Accept: 'application/json' })
)
expect(result.current.isLoading).toBe(true)
await result.waitForUpdate()
expect(result.current.isLoading).toBe(false)
})
I'm also thought might read a bit better if it was like
test('should use fetch', async () => {
const { result, nextUpdate } = renderHook(() =>
useFetch('https://swapi.co/api/people/1', { Accept: 'application/json' })
)
expect(result.current.isLoading).toBe(true)
await nextUpdate()
// may need to call `rerender` before `result.current` can updates, or perhaps `nextUpdate` can take care of that?
expect(result.current.isLoading).toBe(false)
})
I've got no idea how much effort this is, but if anyone want to try to implement it, I'm happy to help, otherwise I'll take a look myself next time I have a free evening.
from react-hooks-testing-library.
We don't actively prevent testing async behaviour, but your hook would need to make the promise/callback/whatever available so that your test runner can be aware of it and so you can delay your assertions.
Can you please share an example of the hook you are trying to test and the rest that is failing and I'll see if I can help get it running green for you.
from react-hooks-testing-library.
@mpeyper : You may refer https://www.npmjs.com/package/react-async#with-usefetch
from react-hooks-testing-library.
useFetch is actually a good example of what I am trying to achieve. I don't have an example to share yet, but I will try to provide one as soon as I can.
from react-hooks-testing-library.
I'm just wondering if this could be improved with a result.onUpdate
callback or something?
import fetch from 'node-fetch'
import { useFetch } from 'react-async'
import { renderHook, cleanup } from 'react-hooks-testing-library'
window.fetch = fetch
describe('useFetch tests', () => {
afterEach(cleanup)
test('should use fetch', (done) => {
const { result, rerender } = renderHook(() =>
useFetch('https://swapi.co/api/people/1', { Accept: 'application/json' })
)
expect(result.current.isLoading).toBe(true)
result.onUpdate(() => {
expect(result.current.isLoading).toBe(false)
done()
})
})
})
or perhaps Promise
based?
import fetch from 'node-fetch'
import { useFetch } from 'react-async'
import { renderHook, cleanup } from 'react-hooks-testing-library'
window.fetch = fetch
describe('useFetch tests', () => {
afterEach(cleanup)
test('should use fetch', () => {
const { result, rerender } = renderHook(() =>
useFetch('https://swapi.co/api/people/1', { Accept: 'application/json' })
)
expect(result.current.isLoading).toBe(true)
return result.waitForUpdate().then(() => {
expect(result.current.isLoading).toBe(false)
})
})
})
Thoughts?
from react-hooks-testing-library.
The example with the callbacks, even if I hate callbacks, would actually allow me to use this library, so I am happy with it.
It would be great to have a way to watchForUpdate. This would allow us to use async/await and we wouldn't be forced to use callbacks. I prefer this method, but it might be harder to implement.
About the warning that is triggered, there is already a PR allowing to pass async stuff to act that should fix this issue on react so I wouldn't worry about it too much. facebook/react#14853
from react-hooks-testing-library.
An example that should be harder to test:
https://codesandbox.io/s/7ok779l6n6?fontsize=14
from react-hooks-testing-library.
Anyone interested should jump on that PR and give me some feedback.
from react-hooks-testing-library.
I will not be able to test it until a couple of days, but it seems to be exactly what I needed ;)
from react-hooks-testing-library.
Actually I suggested some changes
from react-hooks-testing-library.
Sorry I didn't meant to close the issue, but to cancel my comment. I'm a noob ;)
from react-hooks-testing-library.
Related Issues (20)
- [Jest] Snapshot serializer not working HOT 1
- Critical dependency: the request of a dependency is an expression HOT 5
- renderHook() does not clean useRef in custom hooks HOT 2
- useHistory in react-router-dom v5 HOT 2
- renderHook does not work with React Magnetic DI wrapper HOT 1
- Getting error: ReferenceError: document is not defined HOT 8
- Warning: ReactDOM.render is no longer supported in React 18. HOT 1
- Why does the UI not update when calling a hook method? HOT 1
- Error when installing with React 18.x HOT 1
- Migration to react 18 HOT 1
- Testing custom hooks that needs the DOM
- Cannot test async useCallback in custom hook HOT 4
- `restoreConsole` is not a function error if a test fails `beforeEach()` HOT 2
- Cannot test hook raises an error HOT 1
- jsdom environment issues HOT 1
- [renderHook] rerender with new props, new props are not consumed HOT 9
- Lib incompatible with [email protected] version HOT 3
- Stateful context not updating properly HOT 3
- type of `wrapper` might be wrong HOT 1
- `renderHook` result with `vitest` and `react@18` always returns `null` HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-hooks-testing-library.