如何在玩笑中模拟/间谍useState钩子? [英] How to mock/spy useState hook in jest?
问题描述
我试图监视useState React钩子,但我总是使测试失败
I am trying to spy on useState React hook but i always get the test failed
这是我的React组件:
This is my React component:
const Counter= () => {
const[counter, setCounter] = useState(0);
const handleClick=() => {
setCounter(counter + 1);
}
return (
<div>
<h2>{counter}</h2>
<button onClick={handleClick} id="button">increment</button>
</div>
)
}
counter.test.js :
it('increment counter correctlry', () => {
let wrapper = shallow(<Counter/>);
const setState = jest.fn();
const useStateSpy = jest.spyOn(React, 'useState');
useStateSpy.mockImplementation((init) => [init, setState]);
const button = wrapper.find("button")
button.simulate('click');
expect(setState).toHaveBeenCalledWith(1);
})
不幸的是,这不起作用,并且我收到测试失败并显示以下消息:
Unfortunately this doesn't work and i get the test failed with that message:
expected 1
Number of calls: 0
推荐答案
您需要使用 React.useState
而不是单个导入的 useState
.
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
_react.useState // useState
_react.default.useState // React.useState;
因此,您监视 _react.default.useState
,但是您的组件使用了 _react.useState
.似乎不可能监视一次导入,因为您需要该函数属于一个对象,因此,这是一个非常详尽的指南,其中介绍了模拟/监视模块的方法
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
就像@Alex Mackay提到的那样,您可能想改变关于测试反应组件的思维方式,建议您改用react-testing-library,但是如果您确实需要坚持使用酶,则无需走太远嘲笑反应库本身
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
这篇关于如何在玩笑中模拟/间谍useState钩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!