javascript函数内变量的测试值 - sinon / chai

时间:2017-09-11 07:09:11

标签: javascript unit-testing sinon chai

我在React组件中有以下功能:

parentFunction: function(items){
  let variableOfInterest = this.callThisFunction().toArray().filter((ele) => {
    if(obj[ele.get('id')]){
      return ele
    }
  }).map((ele) => ele.get('id'))

  this.setState({newState:variableOfInterest})
}

我能够使用存根编写一个调用callThisFunction的测试,但是无法弄清楚是否可以使用sinon或chai来监视variableOfInterest的值。我想写一个测试,我可以传入一个参数,并使用'expect'来测试结果的值。在最后返回值并没有多大意义 - 这样做只是为了测试似乎没必要。 我也希望能够测试调用toArray()的结果,并且如果可能的话还可以过滤()。感谢您的任何见解!

这是我调用callThisFunction()的测试:

it('should call callThisFunction() once', () => {   
  let callThisFunctionStub = sinon.stub(prototype, 'callThisFunction')
  let stub = callThisFunctionStub.callsFake(() => objectToReturn)
  prototype.callParentFunction(items)
  sinon.assert.calledOnce(stub)
})

1 个答案:

答案 0 :(得分:1)

  

我想写一个测试,我可以传入一个参数,然后使用   '期望'来测试结果的价值。

选项1:

您只需使用该状态即可获取newState的更新值,并将其与预期值进行比较。

使用airbnb/enzyme库来测试您的React组件,可以非常轻松地完成此操作。酶也使用mochachai,因此语法几乎相同。它还提供了间谍和模拟API,如果你想使用它们 - 尽管在这种情况下你可能不需要。

以下是通过浅层渲染获取.state()的API示例:

const wrapper = shallow(<MyComponent />);
expect(wrapper.state().foo).to.equal(10);
expect(wrapper.state('foo')).to.equal(10);

所以你需要为具有parentFunction的Component编写测试,对该Component进行浅层安装,模拟parentFunction的调用,然后获取state并检查它值。

选项2:

如果您不想检查状态,或者想要为variableOfInterest的计算编写更多涉及的测试,您可以尝试将计算代码移动到另一个函数中,并为编写测试那个功能。