使用Jest测试React Component函数

Fer*_*gre 32 javascript reactjs reactjs-flux jestjs

原版的

首先,我遵循Flux架构.

我有一个指示器显示几秒钟,例如:30秒.每一秒它显示1秒减少,所以29,28,27直到0.当到达0时,我清除间隔,使其停止重复.而且,我触发了一个动作.调度此操作后,我的商店会通知我.因此,当发生这种情况时,我将间隔重置为30秒,依此类推.组件看起来像:

var Indicator = React.createClass({

  mixins: [SetIntervalMixin],

  getInitialState: function(){
    return{
      elapsed: this.props.rate
    };
  },

  getDefaultProps: function() {
    return {
      rate: 30
    };
  },

  propTypes: {
    rate: React.PropTypes.number.isRequired
  },

  componentDidMount: function() {
    MyStore.addChangeListener(this._onChange);
  },

  componentWillUnmount: function() {
    MyStore.removeChangeListener(this._onChange);
  },

  refresh: function(){
    this.setState({elapsed: this.state.elapsed-1})

    if(this.state.elapsed == 0){
      this.clearInterval();
      TriggerAnAction();
    }
  },

  render: function() {
    return (
      <p>{this.state.elapsed}s</p>
    );
  },

  /**
   * Event handler for 'change' events coming from MyStore
   */
  _onChange: function() {
    this.setState({elapsed: this.props.rate}
    this.setInterval(this.refresh, 1000);
  }

});

module.exports = Indicator;
Run Code Online (Sandbox Code Playgroud)

组件按预期工作.现在,我想用Jest测试它.我知道我可以使用renderIntoDocument,然后我可以setTimeout为30s并检查我的component.state.elapsed是否等于0(例如).

但是,我想在这里测试的是不同的东西.我想测试是否调用了刷新函数.此外,我想测试当我的经过状态为0时,它会触发我的TriggerAnAction().好吧,我尝试做的第一件事:

jest.dontMock('../Indicator');

describe('Indicator', function() {
  it('waits 1 second foreach tick', function() {

    var React = require('react/addons');
    var Indicator = require('../Indicator.js');
    var TestUtils = React.addons.TestUtils;

    var Indicator = TestUtils.renderIntoDocument(
      <Indicator />
    );

    expect(Indicator.refresh).toBeCalled();

  });
});
Run Code Online (Sandbox Code Playgroud)

但是在编写npm测试时我收到以下错误:

Throws: Error: toBeCalled() should be used on a mock function
Run Code Online (Sandbox Code Playgroud)

我从ReactTestUtils看到了一个mockComponent函数但是给出了解释,我不确定它是否是我需要的.

好的,在这一点上,我被困住了.任何人都可以告诉我如何测试我上面提到的两件事情吗?


更新1,基于Ian答案

这是我试图运行的测试(参见某些行中的注释):

jest.dontMock('../Indicator');

describe('Indicator', function() {
  it('waits 1 second foreach tick', function() {

    var React = require('react/addons');
    var Indicator = require('../Indicator.js');
    var TestUtils = React.addons.TestUtils;

    var refresh = jest.genMockFunction();
    Indicator.refresh = refresh;

    var onChange = jest.genMockFunction();
    Indicator._onChange = onChange;

    onChange(); //Is that the way to call it?

    expect(refresh).toBeCalled(); //Fails
    expect(setInterval.mock.calls.length).toBe(1); //Fails

    // I am trying to execute the 1 second timer till finishes (would be 60 seconds)
    jest.runAllTimers();

    expect(Indicator.state.elapsed).toBe(0); //Fails (I know is wrong but this is the idea)
    expect(clearInterval.mock.calls.length).toBe(1); //Fails (should call this function when time elapsed is 0)

  });
});
Run Code Online (Sandbox Code Playgroud)

我仍然误解了一些事情......

Mic*_*ley 46

看起来你走在正确的轨道上.为了确保每个人都在同一页面上获得这个答案,让我们先找一些术语.

模拟:由单元测试控制的行为的函数.您通常使用mock函数替换某些对象上的实函数,以确保正确调用mock函数.除非您调用jest.dontMock该模块的名称,否则Jest会自动为模块上的每个函数提供模拟.

组件类:这是返回的东西React.createClass.您可以使用它来创建组件实例(它比这更复杂,但这足以满足我们的目的).

组件实例:组件类的实际呈现实例.这是你打电话TestUtils.renderIntoDocument或许多其他TestUtils功能后得到的.


在您的问题的更新示例中,您正在生成模拟并将它们附加到组件而不是组件的实例.此外,您只想模拟要监视或以其他方式更改的功能; 例如,你嘲笑_onChange,但你真的不想,因为你希望它正常行为 - 它只是refresh你想要模拟.

这是我为这个组件编写的一组测试; 评论是内联的,所以如果您有任何问题,请发表评论.对于这个例子和测试套件充分,工作源是在https://github.com/BinaryMuse/so-jest-react-mock-example/tree/master ; 你应该能够克隆它并运行它没有任何问题.请注意,我不得不对组件进行一些小的猜测和更改,因为并非所有引用的模块都在您的原始问题中.

/** @jsx React.DOM */

jest.dontMock('../indicator');
// any other modules `../indicator` uses that shouldn't
// be mocked should also be passed to `jest.dontMock`

var React, IndicatorComponent, Indicator, TestUtils;

describe('Indicator', function() {
  beforeEach(function() {
    React = require('react/addons');
    TestUtils = React.addons.TestUtils;
    // Notice this is the Indicator *class*...
    IndicatorComponent = require('../indicator.js');
    // ...and this is an Indicator *instance* (rendered into the DOM).
    Indicator = TestUtils.renderIntoDocument(<IndicatorComponent />);
    // Jest will mock the functions on this module automatically for us.
    TriggerAnAction = require('../action');
  });

  it('waits 1 second foreach tick', function() {
    // Replace the `refresh` method on our component instance
    // with a mock that we can use to make sure it was called.
    // The mock function will not actually do anything by default.
    Indicator.refresh = jest.genMockFunction();

    // Manually call the real `_onChange`, which is supposed to set some
    // state and start the interval for `refresh` on a 1000ms interval.
    Indicator._onChange();
    expect(Indicator.state.elapsed).toBe(30);
    expect(setInterval.mock.calls.length).toBe(1);
    expect(setInterval.mock.calls[0][1]).toBe(1000);

    // Now we make sure `refresh` hasn't been called yet.
    expect(Indicator.refresh).not.toBeCalled();
    // However, we do expect it to be called on the next interval tick.
    jest.runOnlyPendingTimers();
    expect(Indicator.refresh).toBeCalled();
  });

  it('decrements elapsed by one each time refresh is called', function() {
    // We've already determined that `refresh` gets called correctly; now
    // let's make sure it does the right thing.
    Indicator._onChange();
    expect(Indicator.state.elapsed).toBe(30);
    Indicator.refresh();
    expect(Indicator.state.elapsed).toBe(29);
    Indicator.refresh();
    expect(Indicator.state.elapsed).toBe(28);
  });

  it('calls TriggerAnAction when elapsed reaches zero', function() {
    Indicator.setState({elapsed: 1});
    Indicator.refresh();
    // We can use `toBeCalled` here because Jest automatically mocks any
    // modules you don't call `dontMock` on.
    expect(TriggerAnAction).toBeCalled();
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 这个答案非常惊人(与您的回购中的完整示例相同).谢谢!现在我更了解Jest的工作原理.只有一个注释,我在另一个文件中有我的SetIntervalMixin,所以为了让它运行,还需要调用jest.dontMock('../ SetIntervalMixin'); (2认同)
  • 谢谢你这个非常彻底的答案.我试图在需要商店并遇到麻烦的组件上模拟它.我正在使用`jest.dontMock('./ Store'),但看起来Jest仍然试图嘲笑它.我为商店收到消息"无法调用方法'注册'未定义".你也遇到过这种情况吗? (2认同)

小智 6

我想我明白你在问什么,至少是它的一部分!

从错误开始,您看到的原因是因为您已指示开玩笑不模拟指标模块,因此所有内部都是您编写的.如果你想测试那个特定的函数被调用,我建议你创建一个模拟函数并使用它来代替......

var React = require('react/addons');
var Indicator = require('../Indicator.js');
var TestUtils = React.addons.TestUtils;

var refresh = jest.genMockFunction();
Indicator.refresh = refresh; // this gives you a mock function to query
Run Code Online (Sandbox Code Playgroud)

接下来要注意的是,您实际上是在示例代码中重新分配Indicator变量,因此为了正确行为,我将重命名第二个变量(如下所示)

var indicatorComp = TestUtils.renderIntoDocument(<Indicator />);
Run Code Online (Sandbox Code Playgroud)

最后,如果你想测试的东西,随时间变化,周围使用定时器操纵TestUtils功能(http://facebook.github.io/jest/docs/timer-mocks.html).在你的情况下,我认为你可以这样做:

jest.runAllTimers();

expect(refresh).toBeCalled();
Run Code Online (Sandbox Code Playgroud)

或者,也许稍微不那么挑剔的是依靠setTimeout和setInterval的模拟实现来推理你的组件:

expect(setInterval.mock.calls.length).toBe(1);
expect(setInterval.mock.calls[0][1]).toBe(1000);
Run Code Online (Sandbox Code Playgroud)

还有一两件事,对于任何的上述变化的工作,我想你会需要手动触发的onChange方法,您的组件将首先与您的商店的嘲笑版工作,所以没有更改事件将会发生.您还需要确保已设置jest以忽略react模块,否则它们也将被自动模拟.

全面提出测试

jest.dontMock('../Indicator');

describe('Indicator', function() {
  it('waits 1 second for each tick', function() {
    var React = require('react/addons');
    var TestUtils = React.addons.TestUtils;

    var Indicator = require('../Indicator.js');
    var refresh = jest.genMockFunction();
    Indicator.refresh = refresh;

    // trigger the store change event somehow

    expect(setInterval.mock.calls.length).toBe(1);
    expect(setInterval.mock.calls[0][1]).toBe(1000);

  });

});
Run Code Online (Sandbox Code Playgroud)