预期的通话次数:> = 1已接的通话次数:0 [英] Expected number of calls: >= 1 Received number of calls: 0
本文介绍了预期的通话次数:> = 1已接的通话次数:0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习带有钩子的reactjs表单,现在我想使用玩笑和酶在提交时测试表单.
I am learning reactjs form with hooks, now I would like to test form on submit using jest and enzyme.
这是我的登录组件.
import React from 'react'
function Login() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
// ....api calLS
}
return (
<div>
<form onSubmit={handleSubmit} className="login">
<input type="email" id="email-input" name="email" value={email} onChange={e => setEmail(e.target.value)} />
<input type="password" id="password-input" name="password" value={password} onChange={e =>setPassword(e.target.value)} />
<input type="submit" value="Submit" />
</form>
</div>
)
}
export default Login
这是login.test.js文件
Here is is login.test.js file
it('should submit when data filled', () => {
const onSubmit = jest.fn();
const wrapper = shallow(<Login />)
const updatedEmailInput = simulateChangeOnInput(wrapper, 'input#email-input', 'test@gmail.com')
const updatedPasswordInput = simulateChangeOnInput(wrapper, 'input#password-input', 'cats');
wrapper.find('form').simulate('submit', {
preventDefault: () =>{}
})
expect(onSubmit).toBeCalled()
})
不幸的是,当我运行npm test
时,出现以下错误
Unfortunately when I run npm test
I get the following error
我该怎么做才能解决此错误或测试表格上的教程?
What do I need to do to solve this error or tutorial on testing form?
推荐答案
问题在这里,您创建了一个模拟,但未被测试的组件使用.
Issue here is you created a mock but it is not being consumed by the component you are testing.
const onSubmit = jest.fn(); // this is not being used by <Login />
一种解决方案是模拟您在代码中用注释// ....api calLS
描述的api调用,并验证那些调用是否成功.
A solution to this would be to mock the api calls you described on your code with the comment // ....api calLS
and verify those are called successfully.
import { submitForm } from './ajax.js'; // the function to mock--called by handleSubmit
jest.mock('./ajax.js'); // jest mocks everything in that file
it('should submit when data filled', () => {
submitForm.mockResolvedValue({ loggedIn: true });
const wrapper = shallow(<Login />)
const updatedEmailInput = simulateChangeOnInput(wrapper, 'input#email-input', 'test@gmail.com')
const updatedPasswordInput = simulateChangeOnInput(wrapper, 'input#password-input', 'cats');
wrapper.find('form').simulate('submit', {
preventDefault: () =>{}
})
expect(submitForm).toBeCalled()
})
有用的链接
查看全文