在React Js中使用Jest测试功能 [英] Test function with Jest in React Js

查看:62
本文介绍了在React Js中使用Jest测试功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是React和Test的新手,所以请原谅这个问题.我有一个React表单组件,其输入上的 onChance 运行一个功能 handleChange .试图用Jest对其进行测试,但无法使其正常工作.

I'm new to React and testing in general so forgive the naivety of the question. I have a React form component which onChance on the inputs runs a function handleChange. Tried to test it with Jest but can't make it work.

这是登录"组件:

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();

})

快照测试可以顺利通过,但是在这最后一次尝试中,我的功能测试失败并显示:

The snapshot test passes fine, but in this last attempt my function test fails with:

TypeError: Cannot read property 'target' of undefined

猜猜我需要向函数传递一些东西吗?有点困惑!

Guess I need to pass something to the function? Bit confused!

预先感谢您的帮助.

更新:

更改了测试,如下所示,但测试失败: expect(jest.fn()).toBeCalled()预期已调用了模拟函数.

changed the test as follows but test fails with: 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();

})

推荐答案

在以下位置找到了解决方案:酶模拟onChange事件

Found the solution in here: 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(); 才能正常工作!

It needed this login.update(); in order to work!

感谢大家的帮助!

这篇关于在React Js中使用Jest测试功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆