相关疑难解决方法(0)

用笑话和酶窥探 React 功能组件方法;无法窥探原始值

我正在尝试测试一个 React 组件并确保当它的按钮被点击时,正确的方法被调用。但是,当我尝试运行我的测试并尝试监视该方法时,我收到以下消息:

错误:无法监视原始值;给定的未定义

如何测试单击按钮时是否调用了正确的方法?谢谢!

示例组件.jsx:

import * as React from 'react';

const SampleComponent = () => {
  const sampleMethod = () => {
    console.log('hello world');
  };

  return <button onClick={sampleMethod} type="button">Click Me</button>;
};

export default SampleComponent;
Run Code Online (Sandbox Code Playgroud)

sampleComponent.test.jsx:

import * as React from 'react';
import { shallow } from 'enzyme';
import SampleComponent from './sample';

test('testing spy', () => {
  const spy = jest.spyOn(SampleComponent.prototype, 'sampleMethod');
  const wrapper = shallow(<SampleComponent />);
  wrapper.find('button').simulate('click');
  expect(spy).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs jestjs enzyme

17
推荐指数
2
解决办法
1万
查看次数

如何在反应中使用笑话和酶测试表单提交?

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

 describe('my sweet test', () => {
    it('clicks it', () => {
      
       const wrapper …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing reactjs jestjs enzyme

8
推荐指数
1
解决办法
2万
查看次数

标签 统计

enzyme ×2

jestjs ×2

reactjs ×2

unit-testing ×2

javascript ×1