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

标签 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})
}

我能够使用 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 还使用 mochachai,因此语法几乎相同。它还提供了一个 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/

相关文章:

javascript - 使用 D3.JS 而非纯 Javascript 查找数组数组的最小值和最大值

javascript - 在 Cucumber.js 中是否可以列出所有可用的步骤?

javascript - 如何使用 Mocha、Chai 和 Sinon 正确测试 Express Controller 方法

node.js - sinon.js - 如何组织我的 stub ?

node.js - 如果在测试过程中无法重现错误,如何测试 catch 子句?

javascript - Sinon stub 传递参数

javascript - 不使用 Flash 复制到剪贴板

javascript - 如何等待浏览器关闭直到服务器调用完成?

c# - 在 ASP.NET Core 1.1 中自动生成单元测试

android - 对 WebView 的 WebViewClient 回调的 onPageStarted 和 onPageFinished 进行单元测试