Skip to content

[Bug]: toThrow does not fail test on mismatch of Error#cause #15316

@steveluscher

Description

@steveluscher

Version

30.0.0-alpha.6

Steps to reproduce

it('should check error cause', () => {
  const fn = () => {
    throw new Error('error message', { cause: { code: '1234' } });
  };
  expect(fn).toThrow({
    name: 'Error',
    message: 'error message',
    cause: { code: 'random string' },
  });
});

Expected behavior

The test should fail, owing to the mismatch of Error#cause.

Actual behavior

The test passes.

Additional context

This is a re-file of #15111 which was auto-closed for inactivity. Updated to note that this is still a problem in Jest v30.

This appears to be because Jest only does cause-matching when the cause property is an instance of Error.

https://github.com/jestjs/jest/blob/main/packages/expect/src/toThrowMatchers.ts#L481-L483

This is inappropriate, since the value of cause is allowed to be any type.

Environment

System:
    OS: Linux 5.15 Ubuntu 22.04.4 LTS 22.04.4 LTS (Jammy Jellyfish)
    CPU: (64) x64 AMD EPYC 7502P 32-Core Processor
  Binaries:
    Node: 20.16.0 - ~/n/bin/node
    Yarn: 1.22.22 - ~/.local/share/pnpm/yarn
    npm: 10.8.1 - ~/n/bin/npm
    pnpm: 9.9.0 - ~/.local/share/pnpm/pnpm
  npmPackages:
    jest: ^30.0.0-alpha.6 => 30.0.0-alpha.6

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions