【发布时间】:2022-06-11 15:54:41
【问题描述】:
我需要测试以下使用我的自定义钩子的组件。
import { useMyHook } from 'hooks/useMyHook';
const MyComponent = () => {
const myHookObj = useMyHook();
const handler = () => {
myHookObj.myMethod(someValue)
}
return(
<button onClick={handler}>MyButton</button>
);
};
这是我的测试文件:
jest.mock('hooks/useMyHook', () => {
return {
useMyHook: () => {
return {
myMethod: jest.fn(),
};
},
};
});
describe('<MyComponent />', () => {
it('calls the hook method when button is clicked', async () => {
render(<MyComponent {...props} />);
const button = screen.getByText('MyButton');
userEvent.click(button);
// Here I need to check that the `useMyHook.method`
// was called with some `value`
// How can I do this?
});
});
我需要检查 useMyHook.method 是否被一些 value 调用。
我还想从多个it 案例中对其进行测试,并且可能在每次测试中使用不同的值调用它。
我该怎么做?
【问题讨论】:
标签: reactjs react-hooks jestjs mocking react-testing-library