【问题标题】:Test a React Component function with Jest用 Jest 测试一个 React 组件函数
【发布时间】:2014-10-21 09:14:51
【问题描述】:

原创

首先,我遵循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;

组件按预期工作。现在,我想用 Jest 测试它。我知道我可以使用 renderIntoDocument,然后我可以 setTimeout of 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();

  });
});

但我在编写 npm test 时收到以下错误:

Throws: Error: toBeCalled() should be used on a mock function

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

好的,在这一点上,我被卡住了。谁能告诉我如何测试我上面提到的两件事?


更新 1,基于 Ian 的回答

这就是我正在尝试运行的测试(请参阅某些行中的 cmets):

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)

  });
});

我还是误会了什么……

【问题讨论】:

  • 我现在在工作中遇到完全同样的问题。感谢您花时间写一个问题并希望得到答案
  • 我相信toBeCalled 仅在模拟上有效,而不是实际功能,例如由jest.genMockFunction() 返回。见facebook.github.io/jest/docs/mock-functions.html#content;大概你需要用模拟实现替换Indicator.refresh
  • 嗨,布兰登。但我要测试的是,我的组件是否在必须调用该函数时调用它。所以,我不确定在这种情况下如何使用模拟函数。

标签: javascript reactjs reactjs-flux jestjs


【解决方案1】:

看来您走在正确的轨道上。为了确保每个人都在同一个页面上获得这个答案,让我们把一些术语排除在外。

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

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

组件实例:组件类的实际渲染实例。这是您在调用 TestUtils.renderIntoDocument 或许多其他 TestUtils 函数后得到的结果。


在您问题的更新示例中,您正在生成模拟并将它们附加到组件 class 而不是组件的 instance 。此外,您只想模拟要监视或更改的功能;例如,您模拟 _onChange,但您并不想这样做,因为您希望它正常运行——您只想模拟 refresh

这是我为这个组件编写的一组建议的测试; cmets 是内联的,所以如果您有任何问题,请发表评论。此示例和测试套件的完整工作源位于 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();
  });
});

【讨论】:

  • 这个答案非常棒(与您的仓库中的完整示例相同)。谢谢!现在我对 Jest 的工作原理有了更多了解。只有一条评论,我的 SetIntervalMixin 在另一个文件中,所以为了让它运行,还需要调用 jest.dontMock('../SetIntervalMixin');
  • 感谢您提供如此详尽的回答。我正在尝试在需要商店并且遇到麻烦的组件上模拟它。我正在使用 `jest.dontMock('./Store') 但看起来 Jest 仍在尝试模拟它。我收到 Store 的消息“无法调用未定义的方法‘注册’”。你也遇到过这种情况吗?
  • 在完成我最初的 Jest 设置后,我发现自己在这里被另一个不相关的问题所引导。这个很好的答案再次帮助了我!我希望我能投票两次。
【解决方案2】:

我想我明白你在问什么,至少部分明白了!

从错误开始,您看到的原因是您已指示 jest 不要模拟指标模块,因此所有内部结构都与您编写的一样。如果您想测试调用的特定函数,我建议您创建一个模拟函数并改用它...

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

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

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

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

jest.runAllTimers();

expect(refresh).toBeCalled();

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

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

另一件事,要使上述任何更改生效,我认为您需要手动触发 onChange 方法,因为您的组件最初将使用 Store 的模拟版本,因此不会发生更改事件。您还需要确保已将 jest 设置为忽略反应模块,否则它们也会被自动模拟。

建议的完整测试

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

  });

});

【讨论】:

  • 嗨,Ian,感谢您抽出宝贵的时间来写这样的答案。现在我了解了更多概念,但是,我仍然无法运行我的测试。我根据您的回答使用我尝试运行的测试更新了我的问题。还是有问题。
  • 我想知道// trigger the store change event somehow 部分的内容。这是否以某种方式被嘲笑,或者您可以做类似Store.trigger('change') 的事情吗?我知道这实际上不起作用,但只是从概念上讲,您如何在不向调度程序发送操作的情况下触发该触发器?
猜你喜欢
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多