我有一个 React 表单包装器,它采用类型为函数的 onSubmit Prop ,我想测试它是否使用正确的表单值进行调用。如果我立即检查它,它会失败,但如果我将检查放在 100 毫秒的超时后,它就会通过。
所以看起来好像需要某种处理时间才能执行函数,但是超时太慢了......
例子
test('onSubmit function is called with correct form values', () => {
const defaults = {
email: 'superadmin@gmail.com',
password: 'soSoSecret!'
};
const submitFunction = jest.fn();
const wrapper = mount(<LoginForm onSubmit={submitFunction} />);
// input form values
wrapper
.find('input[name="email"]')
.simulate('change', { target: { value: defaults.email } });
wrapper
.find('input[name="password"]')
.simulate('change', { target: { value: defaults.password } });
expect(submitFunction.mock.calls.length).toBe(0);
wrapper.find('form button[type="submit"]').simulate('click');
// if I test right away, it fails, but if I set timeout for 100ms, it passes
// does the form take time to process and the function be called????
jest.useFakeTimers();
setTimeout(() => {
expect(submitFunction.mock.calls.length).toBe(1);
const args = submitFunction.mock.calls[0][0];
expect(args).toEqual(defaults);
}, 100);
});
是否可以编写这样的没有超时的测试?对我来说似乎是个问题。
感谢阅读! :D
最佳答案
我能想到的一个原因是您正在尝试测试异步发生的事情,而不是立即发生。在这种情况下,您可以尝试使用 async await
PFB 示例:
test('onSubmit function is called with correct form values', async () => {
const defaults = {
email: 'superadmin@gmail.com',
password: 'soSoSecret!'
};
const submitFunction = jest.fn();
const wrapper = mount(<LoginForm onSubmit={submitFunction} />);
// input form values
wrapper
.find('input[name="email"]')
.simulate('change', { target: { value: defaults.email } });
wrapper
.find('input[name="password"]')
.simulate('change', { target: { value: defaults.password } });
expect(submitFunction.mock.calls.length).toBe(0);
await wrapper.find('form button[type="submit"]').simulate('click');
expect(submitFunction.mock.calls.length).toBe(1);
const args = submitFunction.mock.calls[0][0];
expect(args).toEqual(defaults);
});
注意测试用例回调开始前的async
关键字,以及模拟提交按钮点击前的await
关键字。
关于reactjs - React + Jest + Enzyme 表单 onSubmit 测试失败,除非我使用超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59220316/