簡體   English   中英

開玩笑:toHaveBeenCalled()的單元測試不起作用

[英]Jest: Unit test toHaveBeenCalled() not working

我在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時,此操作將失敗。 我檢查了模擬單擊的“ Submit”按鈕時是否調用了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不會。

我設法使該工作正常進行,我從“提交”按鈕中刪除了所有事件,並測試了已調用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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM