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

Viewed 863

I am spying a function in a method that receives an array as its main parameter. The content of that array is irrelevant for me. What I want to check is the length of that array parameter.

// 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 */)

Is there a way of doing this with chai or jest?

1 Answers

You can use sinon: spy.args (Reference);

And check array length / size using chai: .lengthOf (Reference).

For example: (I use 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);
Related