Skip to content
Advertisement

How to mock/spy useState hook in jest?

I am trying to spy on useState React hook but i always get the test failed

This is my React component:

JavaScript

counter.test.js:

JavaScript

Unfortunately this doesn’t work and i get the test failed with that message:

JavaScript

Advertisement

Answer

You need to use React.useState instead of the single import useState.

I think is about how the code gets transpiled, as you can see in the babel repl the useState from the single import ends up being different from the one of the module import

JavaScript

So you spy on _react.default.useState but your component uses _react.useState. It seems impossible to spyOn a single import since you need the function to belong to an object, here is a very extensive guide that explains the ways of mocking/spying modules https://github.com/HugoDF/mock-spy-module-import

And as @Alex Mackay mentioned, you probably want to change your mindset about testing react components, moving to react-testing-library is recommended, but if you really need to stick to enzyme you don’t need to go that far as to mock react library itself

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement