javascriptunit-testingasync-awaitjestjsmocking

Testing exception thrown by mock in Jest


I'm trying to test for an async function to properly handle an exception getting thrown by a dependency call to another async function within its body.

I'm replacing the dependency function with a Jest mock that returns a rejected promise and following guidelines on how to set expectations according to official docs. But I find it's not working as expected. So I built a demo test to check that the exception gets actually thrown but the await expect ... statement doesn't match.

import { jest } from '@jest/globals';

const inner = jest.fn();
const underTest = async () => await inner();

test('async mock throws within async function', async () => {
  inner.mockRejectedValue('Error');

  try {
    await underTest();
    expect('Should not reach this statement').toBeUndefined();
  } catch (err) {
    expect(err).toEqual('Error');
  }
  await expect(underTest()).rejects.toThrow();
});

Notice in the output how the first call the expect statement within the catch block gets reached and passes, but the await expect ... statement below fails as if underTest didn't throw.

$ npm t -- lib/asyncThrow.test.js

> node --experimental-vm-modules node_modules/jest/bin/jest.js lib/asyncThrow.test.js

(node:43103) ExperimentalWarning: VM Modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 FAIL  lib/asyncThrow.test.js
  ✓ mock gets called from async function (2 ms)
  ✕ async mock throws within async function (1 ms)

  ● async mock throws within async function

    expect(received).rejects.toThrow()

    Received function did not throw

      19 |     expect(err).toEqual('Error');
      20 |   }
    > 21 |   await expect(underTest()).rejects.toThrow();
         |                                     ^
      22 | });
      23 |

      at Object.toThrow (node_modules/expect/build/index.js:218:22)
      at Object.<anonymous> (lib/asyncThrow.test.js:21:37)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        0.098 s, estimated 1 s

What am I missing?


Solution

  • Your implementation does reject, but the value doesn't meet the expectation the matcher is checking for. Jest's logic for determining what's thrown looks like this:

        let thrown = null;
    
    
        if (fromPromise && isError(received)) {
          // ...
        } else {
          if (typeof received === 'function') {
            // ...
          } else {
            if (!fromPromise) {
              // ...
            }
          }
        }
    

    In your case, where received = "Error":

    so the result is the default: null.

    As you don't pass any arguments to toThrow, we end up in the default implementation:

      const pass = thrown !== null;
    

    pass is false, and the test fails (the other implementations, e.g. checking the message against a RegExp, all include this check too).

    To have a thrown value in an async test, the promise must reject with an Error:

      inner.mockRejectedValue(new Error('Error'));
    

    Alternatively, use a matcher that reflects the value that's actually being rejected with:

       await expect(underTest()).rejects.toBe('Error');
    

    It's also worth noting that this kind of pattern:

    try {
      doSomething();
      expect(true).toBe(false);
    } catch (err) {
      expect(err).to...
    }
    

    can lead to unexpected outcomes - if the system under test doesn't throw an error, you hit the assertion which does throw an error, then you immediately catch that error. When Jest tries to tell you this, it's a bit of a mess:

        expect(received).toEqual(expected) // deep equality
    
        Expected: "Error"
        Received: [Error: expect(received).toBeUndefined()·
        Received: "Should not reach this statement"]
    

    This is why:

    expect(doSomething).toThrow(...);
    

    and:

    expect(doSomething).rejects...;
    

    are so useful; alternatively, you can explicitly check that the intended assertion is reached with:

    expect.hasAssertions();
    try {
      doSomething();
    } catch (err) {
      expect(err).to...
    }
    

    which provides nicer diagnostics:

        expect.hasAssertions()
    
        Expected at least one assertion to be called but received none.