Uri Klar
Uri Klar

Reputation: 3988

react-testing-library - test component that uses useContext hook - context persists between tests

I'm trying to test a component that uses a custom hook. That hook uses context with the useContext hook. My problem is that the context persists between two consecutive tests. I've tried mocking the context, but that doesn't help.

You can see the code in this codesandbox: https://codesandbox.io/s/l0192w68z though I couldn't get the tests to run there...

I also uploaded it to github where the tests actually run: https://github.com/uriklar/react-testing-library-with-use-context

I'd appreciate any pointers! How can I get a fresh context on every test run.

Thanks!

Upvotes: 5

Views: 5712

Answers (1)

kentcdodds
kentcdodds

Reputation: 29031

The problem is that your <MenuItem /> components are using the same (default) store between tests. There were a few issues actually and I talked about them all in this livestream and here's a pull request showing what things you can do to improve things.

I hope that's helpful!

Upvotes: 11

Related Questions