use*_*622 5 javascript unit-testing reactjs jestjs enzyme
我正在学习带有钩子的reactjs表单,现在我想使用jest和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
Run Code Online (Sandbox Code Playgroud)
这是login.test.js 文件
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()
})
Run Code Online (Sandbox Code Playgroud)
我需要做什么来解决这个错误或测试表格教程?
这里的问题是您创建了一个模拟,但您正在测试的组件没有使用它。
const onSubmit = jest.fn(); // this is not being used by <Login />
Run Code Online (Sandbox Code Playgroud)
解决方案是使用注释模拟您在代码中描述的 api 调用// ....api calLS,并验证这些调用是否成功。
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()
})
Run Code Online (Sandbox Code Playgroud)
免责声明:我对 Enzyme 框架没有经验。
| 归档时间: |
|
| 查看次数: |
36720 次 |
| 最近记录: |