javascript - 如何在 react 中用 Jest 和 enzyme 测试表单提交?

标签 javascript reactjs unit-testing jestjs enzyme

我正在学习带有钩子(Hook)的 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 文件
 describe('my sweet test', () => {
    it('clicks it', () => {
      
       const wrapper = shallow(<Login />);
       const updatedEmailInput = simulateChangeOnInput(wrapper, 'input#email-input', 'blah@gmail.com')
       const updatedPasswordInput = simulateChangeOnInput(wrapper, 'input#password-input', 'death'); 

       expect(updatedEmailInput.props().value).toEqual('blah@gmail.com');
       expect(updatedPasswordInput.props().value).toEqual('death');

       const instance = wrapper.instance()
       const spy = jest.spyOn(instance, 'handleSubmit')
   
       instance.forceUpdate();    
   
       const submitBtn = app.find('#sign-in')
       submitBtn.simulate('click')
       expect(spy).toHaveBeenCalled()

    })
    
  })
不幸的是,当我运行 npm test我收到以下错误。
enter image description here
我需要做些什么来解决此错误,或者有人可以提供有关如何测试表单提交的教程吗?

最佳答案

在文档中,据说您不能将 shallow.instance() 用于功能组件
它将返回空值:https://enzymejs.github.io/enzyme/docs/api/ShallowWrapper/instance.html
在这个话题上也有一个先前的答案
Enzyme instance() returns null
您可以将经过验证的函数 handleSubmit 作为 Prop 传递给 Login,如 How to use jest.spyOn with React function component using Typescript

 // Unit test
  describe('SomeComponent' () => {
  it('validates model on button click', () => {
      const handleSubmit = jest.fn();
      const wrapper = mount(
          <Login handleSubmit={handleSubmit}/>
      );
      const instance = wrapper.instance();
      const submitBtn = app.find('#sign-in')
      submitBtn.simulate('click')
      expect(handleSubmit).toHaveBeenCalled();
    });
  }
您需要在登录组件中调用此测试函数 handleSubmit 作为 onSubmit 的一部分或从上层组件导出整个 onSubmit。导入部分登录功能的登录代码示例
import React from 'react'

function Login( {handleSubmit}) {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    const onSubmit = async (e) => {
        if (handleSubmit) {
          handleSubmit()
        }
        e.preventDefault();
        // ....api calLS
    }
    return (
        <div>
             <form onSubmit={onSubmit} 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

导入提交功能的登录代码示例
import React from 'react'

function Login( {handleSubmit}) {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
   
    // handleSubmit is imported with props
 
    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

关于javascript - 如何在 react 中用 Jest 和 enzyme 测试表单提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64839452/

相关文章:

java - 在 IntelliJ IDEA 中使用 Spring-test-mvc 进行测试更简单的方法?备择方案?

javascript - 表单有效时更改提交按钮颜色

javascript - Material-UI + Next js - TypeError : theme. spacing is not a function

java - 如何访问私有(private)方法内部的对象?

unit-testing - 使用 sinon 断言使用所需参数进行了特定的 stub 调用

javascript - Redux 状态正在更改,但使用 mapStateToProps 时 Prop 未定义

javascript - 防止表单多次提交

javascript - 我的自定义 ShopWare 6 Javascript 插件中未定义“Vue”

javascript - 联系页面设计如何添加Bootstrap

reactjs - 从浏览器调用的 Nextjs 路径返回 404(Nextjs、NGINX)