How to test a specific sequence of calls to the same function with jest

Viewed 784

I have a class I'm trying to test that makes a sequence of calls to a mock function in jest:

the calls I want to test

I have a mock for the Gpio class constructor that creates the object instances behind these properties. The mock class has a mock method for digitalWrite:

mock class

And when I run my test I can see the sequence of calls made to digitalWrite:

the sequence

But I can't figure out how to test that the sequence is correct. I feel like if I can see the sequence in the test fail hint I should be able to say "call first with a 0, then with a 0, then with a 1", but I can't quite figure out how to do it. Any ideas?

Also so that it doesn't get pointed out: I know that technically each of the pin instances should be separate and I should be able to test them individually, but with the way you mock constructors in jest I have to use the same mock function for digitalWrite.

1 Answers

You can use jest's .toHaveBeenNthCalledWith()

e.g.

it('should be called in the following sequence', () => {
  expect(......digitalWrite).toHaveBeenNthCalledWith(1, 0)
  expect(......digitalWrite).toHaveBeenNthCalledWith(2, 0)
  expect(......digitalWrite).toHaveBeenNthCalledWith(3, 1)
})

or you can use the mock function's mock.calls property:

it('should be called in the following sequence', () => {
  expect(......digitalWrite).toHaveProperty('mock.calls', [
    [0], [0], [1]
  ])
})
Related