Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  121] [ 1]  / answers: 1 / hits: 102176  / 7 Years ago, sat, february 11, 2017, 12:00:00

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?


More From » jestjs

 Answers
34

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);
}

[#58976] Thursday, February 9, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zayne

Total Points: 366
Total Questions: 98
Total Answers: 98

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
;