Jest:单元测试toHaveBeenCalled()无效

时间:2018-06-15 21:24:00

标签: javascript reactjs testing jestjs enzyme

我在React中有一个小组件,它在渲染时生成两个随机数,然后要求用户提交这些数字的总和,如果它们是正确的,则增加它们的分数。

以下代码处理此游戏并在浏览器中按预期工作:

import React, { Component } from 'react';

export const randomNumber = () => {
  var maxNumber = 10;
  var randomNumber = Math.floor((Math.random() * maxNumber) + 1);
  return randomNumber;
}

class Arithmetic extends Component {
  constructor(props) {
    super(props);

    this.state = {
      value: '',
      numbers: {
        x: randomNumber(),
        y: randomNumber()
      },
      score: ''
    }

    this.updateVals = this.updateVals.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  updateVals() {
    this.setState({
      numbers: {
        x: randomNumber(),
        y: randomNumber()
      },
      score: this.state.score + 1
    });
  }

  componentDidMount() {
    this.setState({
      score: 0
    });
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    var isCorrect = this.state.numbers.x + this.state.numbers.y == this.state.value ? this.updateVals()  : alert("Try again");
    event.preventDefault();
  }

  render() {
    return (
      <section className="arithmetic">
        <div className="arithmetic__game">
          <div className="row arithmetic__row--details">
            <div className="arithmetic__score">
            Score:&nbsp;&nbsp;{this.state.score}
            </div>
            <div className="arithmetic__timer">
            </div>
          </div>
          <div className="row arithmetic__row--main">
            <div className="arithmetic__examples">
              1 + 1 = 2<br/>
              2 + 1 = 3<br />
            </div> 
            <div className="arithmetic__game-container">
            What is {this.state.numbers.x} + {this.state.numbers.y}?
              <div className="arithmetic__form-container">
                <form onSubmit={this.handleSubmit}>
                  <label>
                    Answer: &nbsp;&nbsp;
                    <input className="input-field" type="text" value={this.state.value} onChange={this.handleChange} />
                  </label>
                  <button className="btn-submit" type="submit" onClick={(e) => (this.handleSubmit) ? this.handleSubmit(e) : null}>Submit</button>
                </form>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }
};

但是,当正确输入两个数字之和时,尝试检查是否调用updateVals时,会失败。我已经检查过是否在模拟单击“提交”按钮时调用了handleSubmit,并调用它。我还检查了数字道具的值,看看状态是否已经正确更新,它们有。

但是,当调用updateVals时,分数会增加(并且再次显示在浏览器中)。但是当我尝试在Jest中模拟这个时,得分保持在0,就像初始化时一样。

我的测试如下:

it("passes with correct input", () => {
      const updateVals = jest.fn();
      const handleSubmit = jest.fn();
      Arithmetic.prototype.updateVals = updateVals;
      Arithmetic.prototype.handleSubmit = handleSubmit;
      let wrapper = mount(<Arithmetic />);

      wrapper.find('.input-field').instance().value = wrapper.update().state().numbers.x + wrapper.update().state().numbers.y;
      expect(wrapper.find('.input-field').instance().value).toEqual((wrapper.update().state().numbers.x + wrapper.update().state().numbers.y).toString());
      wrapper.find('.input-field').simulate('change');
      wrapper.find('.btn-submit').simulate('click');
      console.log(wrapper.update().state().numbers.x, wrapper.update().state().numbers.y, wrapper.update().state().value);
      expect(updateVals).toHaveBeenCalled();
    });

在终端中运行测试表明,例如,如果numbers.x 1 且numbers.y 9 ,则状态中的值键为 '10' 即可。我不确定为什么当我测试handleSubmit时,它会被调用并且测试通过,但updateVals没有。

1 个答案:

答案 0 :(得分:0)

我设法让这个工作,我从提交按钮中删除了任何事件并测试了已经调用onSubmit的表单本身,并测试了该状态下得分本身的更新。

it("passes with correct input", () => {
  const wrapper = shallow(<Arithmetic />);
  const preventDefault = jest.fn();
  const currentScore = wrapper.update().state().score;

  wrapper.find('.input-field').simulate('change', {target: {value: wrapper.update().state().numbers.x + wrapper.update().state().numbers.y}});
  wrapper.find('.main-form').simulate('submit', { preventDefault });
  expect(wrapper.update().state().score).toEqual(currentScore+1);
});