开玩笑的新手-我将如何为此方法编写测试?

时间:2020-02-04 23:07:39

标签: javascript reactjs jestjs

我在下面有这种方法:

onViewed() {
  const { current } = this.state;
  this.slides[current] = { ...this.slides[current], viewed: true };

  const filtered = _.filter(this.slides,
    slide => slide.section === this.slides[current].section);

  if (filtered.every(slide => slide.viewed)) {
    this.onSectionComplete(this.slides[current].section);
  }
}

我对Jest不太了解,想知道如何对这种方法进行单元测试,以便我可以从中学习。我知道期望是方法'onSectionComplete()'是否被触发,但是我不知道您将如何设置来实现这一目标。非常感谢您的帮助。

这是我的测验:

test('method onViewed()', () => {
  const wrapper = shallow(<TutorialCarousel {...mockProps} />);
  wrapper.instance().onViewed();
  expect(wrapper.instance().onSectionComplete).toHaveBeenCalled();
});

谢谢

1 个答案:

答案 0 :(得分:2)

您可以对这样的方法进行监视:

const onSectionComplete = jest.spyOn(TutorialCarousel.prototype, 'onSectionComplete');

const wrapper = shallow(<TutorialCarousel {...mockProps} />);
  wrapper.instance().onViewed();

expect(onSectionComplete).toHaveBeenCalled();