Search code examples
javascriptjestjs

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?


Solution

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