javascript 函数内部变量的测试值 - sinon / chai
Test value of variable inside javascript function - 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' 来测试结果的值。 return 最后的值真的没有意义 - 这样做只是为了测试似乎没有必要。
我也希望能够测试调用 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
,因此语法几乎相同。它还提供了一个间谍和模拟 API,如果你想使用它们——尽管在这种情况下你可能不需要。
这里是API通过浅层渲染得到.state()
的例子:
const wrapper = shallow(<MyComponent />);
expect(wrapper.state().foo).to.equal(10);
expect(wrapper.state('foo')).to.equal(10);
因此您需要为具有 parentFunction
的组件编写测试,对该组件进行浅层安装,模拟 parentFunction
的调用,然后获取 state
和检查它的值。
选项 2:
如果你不想检查状态,或者想为 variableOfInterest
的计算编写更复杂的测试,你可以尝试将计算代码移动到不同的函数中,并为 那个函数。
我在 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' 来测试结果的值。 return 最后的值真的没有意义 - 这样做只是为了测试似乎没有必要。 我也希望能够测试调用 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
,因此语法几乎相同。它还提供了一个间谍和模拟 API,如果你想使用它们——尽管在这种情况下你可能不需要。
这里是API通过浅层渲染得到.state()
的例子:
const wrapper = shallow(<MyComponent />);
expect(wrapper.state().foo).to.equal(10);
expect(wrapper.state('foo')).to.equal(10);
因此您需要为具有 parentFunction
的组件编写测试,对该组件进行浅层安装,模拟 parentFunction
的调用,然后获取 state
和检查它的值。
选项 2:
如果你不想检查状态,或者想为 variableOfInterest
的计算编写更复杂的测试,你可以尝试将计算代码移动到不同的函数中,并为 那个函数。