Skip to content

Fix expect().rejects.toThrow() #5602

Closed
Closed

Description

@Electroid

Shouldn't that be working?

Does this suit your needs?

import { describe, expect, test } from 'bun:test';

const askGPT = async (text: string, prompt: string, context: string): Promise<void> => {
	throw new Error('⛔ API error.');
};

describe('', () => {
	test('', async () => {
		await expect(async () => await askGPT('text', 'prompt', 'context')).toThrow(Error(`⛔ API error.`));
	});
});

This works only in bun, but not in vitest, so it's not compatible. It seems .rejects.toThrow is not implemented correctly or at all in bun, it throws Expected value must be a function on code like this that works in vitest:

await expect(asyncFn()).rejects.toThrow()

Originally posted by @silverwind in #1825 (comment)

Activity

  1. added
    bugSomething isn't working
    bun:testSomething related to the `bun test` runner
    on Sep 17, 2023
  2. mrbrianevans commented on Oct 9, 2023

    @mrbrianevans
    32 |     await expect(async ()=>generator.next()).rejects.toThrow('Unsupported type passed')
                  ^
    error: expect(received).rejects.toThrow(expected)
    
    Expected promise
    Received: [Function: AsyncFunction]
    

    This works when run with jest, but not when run with Bun. The above error output is from running bun test, but when run with jest this test passes.

  3. tghpereira commented on Oct 29, 2023

    @tghpereira

    This bug also happens for synchronous calls.

    Version of Bun is running: 1.0.7+b0393fba6200d8573f3433fb0af258a0e33ac157
    Platform: Linux 6.2.0-35-generic x86_64 x86_64

  4. MauriceArikoglu commented on Jan 27, 2024

    @MauriceArikoglu

    Still happening in bun 1.0.25

  5. di-sukharev commented on Mar 7, 2024

    @di-sukharev

    i do like this:

    expect(
            BalanceWithdrawalService.addWithdrawalToQueue({
              toAddress: targetWallet.address!.toString(true, true, true),
              userId: targetUser.id,
            })
          ).rejects.toThrow("EMPTY_BALANCE");
    

    it works.

    the BalanceWithdrawalService.addWithdrawalToQueue is async

  6. stephenh commented on Apr 2, 2024

    @stephenh

    @Electroid I just upgraded to bun 1.1, and it looks like this has been fixed!

  7. RichAyotte commented on May 22, 2024

    @RichAyotte

    workaround

    const expectedError = new Error()
    try {
      await asyncFunctionThatThrows()
     } catch(error) {
       expect(error).toEqual(expectedError)
    }
  8. MattBDev commented on Jul 9, 2024

    @MattBDev

    I believe I'm experiencing the same issue.
    I have the following code that works with jest but fails with bun:

     it('rejects with a dom exception', () => {
        fetch.mockAbort()
        expect(fetch('/')).rejects.toThrow(expect.any(DOMException))
      })
    

    It results in the following failure:

    error: expect(received).toThrow(expected)
    
    Expected constructor: ExpectAny
    Received constructor: DOMException
    

    The intended behavior that the .toThrow() function should be that toThrow should be checking what ExpectAny holds but it seems in this case toThrow is comparing against ExpectAny directly.

  9. added a commit that references this issue on Jan 22, 2025
    aad1d68
  10. digisomni commented on Feb 23, 2025

    @digisomni

    There seems to be no combination that I can use to get this to work (make a test pass where we expect the object being tested to throw an error), so I definitely believe this to be a bug.

  11. robobun commented on Jun 16, 2026

    @robobun
    Collaborator

    This works correctly now. Verified on Bun v1.4.0:

    const asyncFn = async () => { throw new Error("fail"); };
    await expect(asyncFn()).rejects.toThrow();           // ✓ pass
    await expect(asyncFn()).rejects.toThrow("fail");     // ✓ pass
    await expect(asyncFn()).rejects.toThrow(Error);      // ✓ pass
    
    const p = Promise.reject(new DOMException("aborted", "AbortError"));
    await expect(p).rejects.toThrow(DOMException);       // ✓ pass

    No more Expected value must be a function error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingbun:testSomething related to the `bun test` runner

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions