【问题标题】:How to test form submit with jest and enzyme in react?如何在反应中用玩笑和酶测试表单提交?
【发布时间】:2021-02-26 13:20:13
【问题描述】:

我正在学习带有钩子的 reactjs 表单,现在我想在提交时使用 jest 和酶测试表单。

这是我的登录组件。

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 时,我收到以下错误。

我需要做些什么来解决这个错误,或者有人可以提供有关如何测试表单提交的教程吗?

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs enzyme


    【解决方案1】:

    在文档中说您不能将 shallow.instance() 用于功能组件 它将返回 null:https://enzymejs.github.io/enzyme/docs/api/ShallowWrapper/instance.html 在这个话题上也有一个先前的答案 Enzyme instance() returns null

    您可以将经过验证的函数 handleSubmit 作为道具传递给 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
    
    

    【讨论】:

    • 那么我需要做什么来测试我的表单提交?
    • 你可以像 stackoverflow.com/questions/56297482/…987654324@ 那样将经过验证的函数作为道具传递
    • 你需要在Login组件中使用这个测试handleSubmit函数
    • 可以使用 toHaveBeenCalled 没有时间
    猜你喜欢
    • 2018-07-22
    • 2023-03-27
    • 2021-02-22
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多