我在 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})
}
我能够使用 stub 编写调用 callThisFunction 的测试,但无法弄清楚是否可以使用 sinon 或 chai 来监视 variableOfInterest 的值。我想编写一个测试,我可以在其中传递一个参数,并使用“expect”来测试结果的值。在最后返回值并没有真正意义——而且仅仅为了测试而这样做似乎没有必要。 我也希望能够测试调用 toArray() 和 filter() 的结果(如果可能的话)。感谢您的任何见解!
这是我对调用 callThisFunction() 的测试:
it('should call callThisFunction() once', () => {
let callThisFunctionStub = sinon.stub(prototype, 'callThisFunction')
let stub = callThisFunctionStub.callsFake(() => objectToReturn)
prototype.callParentFunction(items)
sinon.assert.calledOnce(stub)
})
最佳答案
I'd like to write a test where I can pass in an argument, and use 'expect' to test for the result's value.
选项 1:
您可以简单地使用状态来获取 newState
的更新值,并将其与您的期望值进行比较。
这可以很容易地通过使用 airbnb/enzyme
来完成。库来测试你的 React 组件。 Enzyme 还使用 mocha
和 chai
,因此语法几乎相同。它还提供了一个 spy 和模拟 API,如果你想使用它们——尽管在这种情况下你可能不需要。
这是获取 .state()
的 API 示例通过浅渲染:
const wrapper = shallow(<MyComponent />);
expect(wrapper.state().foo).to.equal(10);
expect(wrapper.state('foo')).to.equal(10);
因此您需要为具有parentFunction
的组件编写测试,对该组件进行浅层安装,模拟parentFunction
的调用,然后获取state
并检查其值。
选项 2:
如果你不想检查状态,或者想为 variableOfInterest
的计算编写更复杂的测试,你可以尝试将计算代码移动到不同的函数中,并为那个函数。
关于javascript - javascript 函数中变量的测试值 - sinon/chai,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46149997/