【问题标题】:Expect spy function to have been called with array of certain length期望 spy 函数以一定长度的数组被调用
【发布时间】:2020-10-26 20:20:00
【问题描述】:

我正在窥探方法中的一个函数,该方法接收一个数组作为其主要参数。该数组的 content 对我来说无关。我要检查的是该数组参数的长度

// Main function
public async removeUsers() {
  const inactiveUsers = await this.userRepository.find({ where: { inactive: true } })

  this.userRepository.remove(inactiveUsers)
}

// Test case
const spyUserRepositoryRemove = sinon.spy(UserRepository.prototype, 'remove')
[...]
expect(spyDealRepositoryRemove).to.have.been.calledOnceWith(/* Array of length X */)

有没有办法用 chaijest 做到这一点?

【问题讨论】:

    标签: javascript jestjs mocha.js chai sinon


    【解决方案1】:

    你可以使用sinon:spy.args(Reference);

    并使用 chai 检查数组长度/大小:.lengthOf (Reference)。

    例如:(我用 chai expect)

    // Make sure spy called.
    expect(spyDealRepositoryRemove.calledOnce).to.equal(true);
    // spyDealRepositoryRemove.args[0]: store all arguments used for first call.
    // spyDealRepositoryRemove.args[0][0]: store 1st argument on first call.
    // Make sure that 1st argument on 1st call is array!
    expect(spyDealRepositoryRemove.args[0][0]).to.be.an('array');
    // Verify: array length; for example: 2 members.
    expect(spyDealRepositoryRemove.args[0][0]).to.have.lengthOf(2);
    

    【讨论】:

      猜你喜欢
      • 2017-04-21
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多