expect.assertions(number)

expect.assertions(number) verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.

For example, let's say that we have a function doAsync that receives two callbacks callback1 and callback2, it will asynchronously call both of them in an unknown order. We can test this with:

  1. test('doAsync calls both callbacks', () => {
  2. expect.assertions(2);
  3. function callback1(data) {
  4. expect(data).toBeTruthy();
  5. }
  6. function callback2(data) {
  7. expect(data).toBeTruthy();
  8. }
  9. doAsync(callback1, callback2);
  10. });

The expect.assertions(2) call ensures that both callbacks actually get called.