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?

1

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":

  • fromPromise is true, but;
  • isError(received) is false; and
  • typeof received === 'function' is false;

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật