簡體   English   中英

使用Jest測試React Component函數

[英]Test a React Component function with Jest

原版的

首先,我遵循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為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測試時我收到以下錯誤:

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

我從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)

  });
});

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

看起來你走在正確的軌道上。 為了確保每個人都在同一頁面上獲得這個答案,讓我們先找一些術語。

模擬 :由單元測試控制的行為的函數。 您通常使用mock函數替換某些對象上的實函數,以確保正確調用mock函數。 除非您在該模塊的名稱上調用jest.dontMock ,否則Jest會自動為模塊上的每個函數提供jest.dontMock

組件類 :這是React.createClass返回的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();
  });
});

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

從錯誤開始,您看到的原因是因為您已指示開玩笑不模擬指標模塊,因此所有內部都是您編寫的。 如果你想測試那個特定的函數被調用,我建議你創建一個模擬函數並使用它來代替......

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方法,因為您的組件最初將使用您的商店的模擬版本,因此不會發生任何更改事件。 您還需要確保已設置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);

  });

});

暫無
暫無

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

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