预计来电次数:>= 1 已接来电次数:0

2024-05-04

我正在学习带有钩子的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

这是login.test.js 文件

it('should submit when data filled', () => {
    const onSubmit = jest.fn();
    const wrapper = shallow(<Login />)
    const updatedEmailInput = simulateChangeOnInput(wrapper, 'input#email-input', '[email protected] /cdn-cgi/l/email-protection')
    const updatedPasswordInput = simulateChangeOnInput(wrapper, 'input#password-input', 'cats'); 
    wrapper.find('form').simulate('submit', {
      preventDefault: () =>{}
    })

    expect(onSubmit).toBeCalled()
 })

Unfortunately when I run npm test I get the following error enter image description here

我需要做什么来解决这个错误或测试表格教程?


这里的问题是您创建了一个模拟,但您正在测试的组件没有使用它。

const onSubmit = jest.fn(); // this is not being used by <Login />

解决方案是使用注释模拟您在代码中描述的 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', '[email protected] /cdn-cgi/l/email-protection')
    const updatedPasswordInput = simulateChangeOnInput(wrapper, 'input#password-input', 'cats'); 
    wrapper.find('form').simulate('submit', {
      preventDefault: () =>{}
    })

    expect(submitForm).toBeCalled()
 })

有用的链接

  • 非常相似的问题 https://stackoverflow.com/a/61625562/3915006
  • 模拟模块 https://jestjs.io/docs/en/mock-functions#mocking-modules
  • 理解笑话嘲笑 https://medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c

免责声明:我对 Enzyme 框架没有经验。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

预计来电次数:>= 1 已接来电次数:0 的相关文章

随机推荐