我正在尝试测试在使用该钩子/函数的组件中调用在钩子内部定义的函数。我熟悉模拟简单的模块/函数,但这种情况让我感到困惑,因为我不知道如何仅模拟该挂钩中的单个返回函数而不丢失该挂钩中的所有其他函数/逻辑,而我不这样做不想嘲笑。
假设我有一个看起来像这样的钩子:
import { useState } from 'react';
export const useSomeHook = () => {
const [someValue, setSomeValue] = useState();
const [someOtherValue, setSomeOtherValue] = useState();
// a bunch of other logic in here...
return {
someValue,
setSomeValue,
someOtherValue,
setSomeOtherValue,
}
}
然后我有一个使用该钩子的函数组件:
export const SomeComponent = () => {
const { setSomeValue } = useSomeHook();
return (<button onClick={() => setSomeValue('hey')}>hello</button>);
}
我希望能够测试单击按钮时是否会调用
setSomeValue
。
const mockSetSomeValue = jest.fn();
jest.mock('./useSomeHook.js', () => {
const actual = jest.requireActual('./useSomeHook.js');
return {
...actual,
// This won't work because now everything else inside of useSomeHook is missing and other tests I have in this file will fail
useSomeHook: () => ({
setSomeValue: mockSetSomeValue,
})
}
});
describe('SomeComponent', () => {
it('should call setSomeValue when button is clicked', () => {
render(<SomeComponent />);
// fire event to click button
expect(mockSetSomeValue).toHaveBeenCalledWith('hey');
});
});
这样的事情可能吗?谢谢!
尝试类似:
describe('SomeComponent', () => {
it('should call setSomeValue when button is clicked', () => {
// Dummy.
render(<SomeComponent />);
// With right defaults.
const { someValue } = useSomeHook();
expect(someValue()).toEqual('my-default');
// With trigger.
// ... fire event to click button here ...
// Actual test.
expect(someValue()).toEqual('hey');
});
});
更简单,如果您遵循上面的注释风格,那么您稍后就会确切地知道哪个断言是虚拟的一部分,哪个是实际测试。