Closed sliu-cais closed 9 months ago
Hi @sliu-cais,
Sorry, I missed the notification for this issue. Did you get it sorted in the end?
one thing that immediately jumped out at me was that you are destructing result
which breaks hook updates (see the note in this section of the docs).
Hi @sliu-cais,
Sorry, I missed the notification for this issue. Did you get it sorted in the end?
one thing that immediately jumped out at me was that you are destructing
result
which breaks hook updates (see the note in this section of the docs).
I eventually went with a completely different approach so this wasn't needed in the end. But you're saying if I were to do this it would likely work, correct?
const {
result,
rerender,
} = renderHook(
() => {
return useStateContext({ context: StateContext })
},
{ wrapper: StateProvider }
)
act(() => {
result.current.setState({ a: 1, b: 2, c: 3 })
result.current.rerender()
})
expect(result.current.state).toEqual({ a: 1, b: 2, c: 3 })
expect(result.current.sum).toEqual(6)
act(() => {
result.current.setState({ a: 2, b: 3, c: 4 })
result.current.rerender()
})
expect(result.current.state).toEqual({ a: 2, b: 3, c: 4 })
expect(result.current.sum).toEqual(9)
If so that's good to know, I'll keep that in mind for the future.
Yeah, that should work.
react-hooks-testing-library
version: 8.0.1react
version: 18.2.0react-dom
version (if applicable): 18.2.0react-test-renderer
version (if applicable):node
version: v16.15.0npm
(oryarn
) version: yarn v1.22.19Relevant code or config:
I'm having trouble testing a custom hook that uses a context that basically sets and gets values.
Here's a simplified toy version:
What you did:
If I implement in app it works as expected:
This logs out the new sum correctly when the
useStateContext
is used when buttons are clicked.When I try and test though:
it never updates the state
What happened:
Reproduction:
Codesandbox of code: https://codesandbox.io/s/frosty-maria-ccydpt?file=/src/App.tsx
The test is self contained. You should be able to copy-paste the it.only block and run.
Problem description:
I have a working stateful context that I can verify just by using the app, but cannot seem to test it properly
Suggested solution:
This works:
But this does not, because the usage of the context is outside of the provider:
It appears the test is behaving like the latter, so perhaps wrapper isn't wrapping correctly?