在React Js中使用Jest测试函数

jljoyd4f  于 2023-08-01  发布在  Jest
关注(0)|答案(3)|浏览(158)

我是React和测试的新手,所以请原谅这个问题的天真。我有一个React表单组件,它在输入上运行一个函数handleChange。尝试用Jest测试它,但无法使其工作。
下面是Login组件:

class Login extends React.Component {

  constructor() {
    super();
    this.state = {username: '', password: ''}
    this.disableSubmit = this.disableSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.setState({
      [e.target.name]: e.target.value
    });
  }

  render() {

    return(
      <div className="login">
        <form>
          <h3 className="login__title">LOGIN</h3>
          <div className="input-group">
            <input onChange={this.handleChange} value={this.state.username} className="form-control login__input username" type="text" placeholder="user name" name={'username'} autoFocus/>
          </div>
          <div className="input-group">
            <input onChange={this.handleChange} value={this.state.password} className="form-control login__input password" type="password" placeholder="password" name={'password'}/>
          </div>
          <div>
            <button className="btn btn-primary btn-block login__button" type="submit">Login</button>
          </div>
        </form>
      </div>

    )
  }
}

export default Login;

字符串
这是我的测试:

import React from 'react'
import { shallow, mount } from 'enzyme'
import { shallowToJson } from 'enzyme-to-json'

import {Login} from '../../../src/base/components/index'

describe('Given the Login component is rendered', () => {

  describe('Snapshots', () => {
    let component

    beforeEach(() => {
      component = shallow(<Login />)
    })

    it('should be as expected', () => {
      expect(shallowToJson(component)).toMatchSnapshot()
    })
  })

})

test('Submitting the form should call handleSubmit', () => {

  const startState = {username: ''};
  const handleChange = jest.fn();
  const login = mount(<Login />);
  const userInput = login.find('.username');

  userInput.simulate('change');

  expect(handleChange).toBeCalled();

})


快照测试通过良好,但在最后一次尝试中,我的函数测试失败:

TypeError: Cannot read property 'target' of undefined


我想我需要传递一些东西给函数。有点困惑!
先谢谢你的帮助。
更新:
按如下所述更改测试,但测试失败:expect(jest.fn()).toBeCalled() Expected mock function to have been called.
测试更新:

test('Input should call handleChange on change event', () => {

  const login = mount(<Login />);
  const handleChange = jest.spyOn(login.instance(), 'handleChange');
  const userInput = login.find('.username');
  const event = {target: {name: "username", value: "usertest"}};

  userInput.simulate('change', event);

  expect(handleChange).toBeCalled();

})

slsn1g29

slsn1g291#

是的,您需要向simulate函数传递事件对象。

const event = {target: {name: "special", value: "party"}};

  element.simulate('change', event);

字符串
编辑:哦,你还需要做一些类似的事情:

jest.spyOn(login.instance(), 'handleChange')


但这和你的错误无关

eqoofvh9

eqoofvh92#

在这里找到了解决方案:Enzyme simulate an onChange event

test('Input should call handleChange on change event', () => {

  const event = {target: {name: 'username', value: 'usertest'}};
  const login = mount(<Login />);
  const handleChange = jest.spyOn(login.instance(), 'handleChange');
  login.update(); // <--- Needs this to force re-render
  const userInput = login.find('.username');

  userInput.simulate('change', event);

  expect(handleChange).toBeCalled();

})

字符串
它需要这个login.update();才能工作!
感谢大家的帮助!

hc2pp10m

hc2pp10m3#

handleChange当前未被嘲笑。以下是几种方法:
将更改事件处理程序作为属性传递给Login组件。

<div className="input-group">
  <input 
    onChange={this.props.handleChange} 
    value={this.state.username}
    className="form-control login__input username" 
    type="text"
    placeholder="user name"
    name={'username'}
    autoFocus
    />
</div>

字符串

登录规范.js

...
const handleChange = jest.fn();
const login = mount(<Login handleChange={handleChange}/>);
...


将handleChange替换为模拟函数。

...
const handleChange = jest.fn();
const login = mount(<Login />);
login['handleChange'] = handleChange // replace instance
...
expect(handleChange).toBeCalled();


使用jest spyOn来创建一个 Package 原始函数的模拟函数。

...
const handleChange = jest.spyOn(object, 'handleChange') // will call the original method
expect(handleChange).toBeCalled();


将Login组件上的handleChange替换为模拟函数。... const handleChange = jest.spyOn(object,'handleChange').mock //将调用原来的方法expect(handleChange).toBeCalled();

相关问题