期望使用一定长度的数组调用间谍函数

Expect spy function to have been called with array of certain length

我正在监视 接收数组作为其主要参数的方法中的函数。该数组的 content 对我来说是 irrelevant。我要检查的是 数组参数的长度 .

// 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 做到这一点?

你可以使用 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);