Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

288
Views
In Jest, how can I make a test fail?

I know I could throw an error from inside the test, but I wonder if there is something like the global fail() method provided by Jasmine?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Jest actually uses Jasmine, so you can use fail just like before.

Sample call:

fail('it should not reach here');

Here's the definition from the TypeScript declaration file for Jest:

declare function fail(error?: any): never;

If you know a particular call should fail you can use expect.

expect(() => functionExpectedToThrow(param1)).toThrow();
// or to test a specific error use
expect(() => functionExpectedToThrow(param1)).toThrowError();

See Jest docs for details on passing in a string, regex, or an Error object to test the expected error in the toThrowError method.

For an async call use .rejects

// returning the call
return expect(asyncFunctionExpectedToThrow(param1))
  .rejects();
// or to specify the error message
// .rejects.toEqual('error message');

With async/await you need to mark the test function with async

it('should fail when calling functionX', async () => {
  await expect(asyncFunctionExpectedToThrow(param1))
    .rejects();
  // or to specify the error message
  // .rejects.toEqual('error message');
}

See documentation on .rejects and in the tutorial.

Also please note that the Jasmine fail function may be removed in a future version of Jest, see Yohan Dahmani's comment. You may start using the expect method above or do a find and replace fail with throw new Error('it should not reach here'); as mentioned in other answers. If you prefer the conciseness and readability of fail you could always create your own function if the Jasmine one gets removed from Jest.

function fail(message) {
  throw new Error(message);
}
over 4 years ago · Santiago Trujillo Report

0

You can do it by throwing an error. For example:

test('Obi-Wan Kenobi', () => {
  throw new Error('I have failed you, Anakin')
})
over 4 years ago · Santiago Trujillo Report

0

Copy/pasta failing test:

it('This test will fail', done => {
  done.fail(new Error('This is the error'))
})
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!