Jest: rejects.toThrowError

Created on 18 May 2017  ·  53Comments  ·  Source: facebook/jest

jest version: 20.0.3

For sync method, it works in this way.

test('example', () => {
  function fn() {
    throw new Error('some error');
  }

  expect(fn).toThrowError('some error');
});

toThrowError doesn't work with promises.

test('example', async () => {
  async function fn() {
    throw new Error('some error');
  }

  await expect(fn()).rejects.toThrowError('some error');
});

I am getting an error:

>
expect(function).toThrowError(string)
Received value must be a function, but instead "object" was found

This works! The async function throws a function that throws an error.

test('example', async () => {
  async function fn() {
      const errorFunction = () => {
        throw new Error('some error');
      };
      throw errorFunction;
    }

    await expect(fn()).rejects.toThrowError('some error');
  });

Obiously it doesn't make sense. I can see this line in the source code.
https://github.com/facebook/jest/pull/3068/files#diff-5d7e608b44e8080e7491366117a2025fR25
It should be Promise.reject(new Error()) instead of Promise.reject(() => {throw new Error();}

The example from the docs also doesn't work

test('fetchData() rejects to be error', async () => {
  const drinkOctopus = new Promise(() => {
      throw new Error('yuck, octopus flavor');
  });

  await expect(drinkOctopus).rejects.toMatch('octopus');
});
Help Wanted

Most helpful comment

+1 on this.

I use this for now:

await expect(Promise.rejects(new Error('Some error')))
  .rejects.toMatchObject({
    message: 'Some error',
  });

This is a temporary workaround if you are willing to match the whole error message. Obviously, jest should support such basic thing.

All 53 comments

Try awaiting inside the expect block, as in expect(await drinkOctopus).rejects.toMatch('octopus');

It won't work... an error will be thrown and 'expect' cant catch that.

Found it (I stumbled upon your issue because I had the same problem :))

describe("When a collection is not passed", () => {
      it("Returns an error", async () => {
        await expect(cqrs.MongoEventStore.create()).rejects.toEqual(cqrs.ErrCollectionRequired)
      })
})

Test passes on my machine. I think you can close it now.

What we want is to match a error message (that is, the Error.prototype.message property), just like the documentation says.

Otherwise it's easy to use something like .toEqual(expect.any(Error))

Use toMatch instead of toEqual, then. Unless I missed your point, in which case I apologise.

toMatch is what I want, the point of this bug is that it doesn't work :) See last example in the initial comment.

Apologies, I should not try to help at this late time of the day. I now understood what you mean. It is a good point, but I believe that the example is incorrect, and not the implementation. Let me try to explain what I mean, I hope it makes a tiny bit of sense.
If you look at this (actual) code:

        const collection = {
          createIndex: jest.fn(() => {
            return new Promise((resolve, reject) => { reject(message) })
          })
        }
        await expect(cqrs.MongoEventStore.create(collection)).rejects.toMatch(message)

That works. If you look at the Javascript specification, a Promise does not coerce developers to use Error as a reason for the reject. Yes, that's what some examples specify (as in here), but the specification talks about a generic reason.
In this case, Jest does not make any assumption and tries to match the string against the reason, irrespective of its type.
Does it make any sense at all? I agree that it is not ideal and that some intelligence could be added to extract the message from an Error, but that's too much for tonight :)

My two pennies worth of it.

Mmm I see what you mean. Yet Jest's documentation use the example of a real error with toMatch :) see https://facebook.github.io/jest/docs/expect.html#rejects . Either the example in the doc is wrong, or the implementation is wrong :)

I think this is needlessly difficult to check an error's message with Jest, especially when we want to match.

@imeruli
reject should be called with an Error object, not a literal string because you don't get the stacktrace.
It's definitely a bad practice.

When using async/await you should write

async foo() {
  throw new Error('some error');
}

not

async foo() {
  throw 'some error';
}

Isentkiewicz, I do no not disagree, however, from a specification standpoint, it is written nowhere.

See the "Description" section from the link you referred.

The static Promise.reject function returns a Promise that is rejected. For debugging purposes and selective error catching, it is useful to make reason an instanceof Error.

+1 on this.

I use this for now:

await expect(Promise.rejects(new Error('Some error')))
  .rejects.toMatchObject({
    message: 'Some error',
  });

This is a temporary workaround if you are willing to match the whole error message. Obviously, jest should support such basic thing.

+1 It would be great if I can use reject with an error object .

What about a toRejectWith() that handles that message? This being a specific situation for rejected errors:

await expect(Promise.rejects(new Error('Some error')))
  .rejects.withMessage('Some error');

Or even this:

await expect(Promise.rejects(new Error('Some error')))
  .rejects.message.toMatch('Some error');

As a workaround for this issue, I came up with this aproach:

async function shouldRejectWithError() {
    throw new Error("An example error");
}

it('should reject with an error', async () => {
    let err;

    try {
        await shouldRejectWithError();
    } catch (e) {
        err = e;
    }

    expect(err.message).toMatch(/example/);
});

If it doesn't throw, err will be undefined and fail to read the message property. Otherwise, if it does throw, it verifies the message matches.

Im confused - why does the documentation (still!) contain an example that doesnt work (https://facebook.github.io/jest/docs/en/expect.html#rejects) and prusumedly never worked?

Also why not solve it by having expect().toThrow() support promises? Then you could write:

expect(Promise.rejects(new Error('Some error'))).toThrow('Some error');

+1 same here.
just spent an hour trying to work our why I cant use expect().toThrow() when testing (async) mongoose DB actions & validators (with a not-very-useful jest message "Received value must be a function, but instead "object" was found")

@lachlanhunt that would work, of course, but it is extremely verbose compared to other jest workflows. Probably you also want to check before hand that err is actually defined (there was an error thrown), otherwise it'll give an unhelpful undefined error.

BTW, for anyone reading so far, @ecstasy2 solution stopped working on Jest 21.0: https://github.com/facebook/jest/issues/4532

You can do expect(Promise.reject(new Error('something'))).rejects.toHaveProperty('message', 'something else'); which gives:

image

To test multiple properties, the following is working:

expect(promise).rejects.toHaveProperty('prop1', 'value1');
expect(promise).rejects.toHaveProperty('prop2', 'value2');

Is this considered a bug or just the way Jest is supposed to work?
If the latter is true, the documentation should reflect this. Currently it says you can use:

await expect(drinkOctopus).rejects.toMatch('octopus');

Which doesn't actually work if drinkOctopus is an instance of an Error, which as discussed earlier is considered "best practice". The toMatchObject solution mentioned previously doesn't work as of Jest 21, so you are reduced to things like toHaveProperty, which work, but doesn't support partial matching.

This feels cumbersome, to me. Is there a planned way to handle these rejections?

IMO it's a bug (or missing feature, I suppose) (and as this has never been closed, I'm guessing other collaborators agree with me). Not really sure how to achieve symmetry with other matchers, but .toThrowErrorshould support (rejected) promises. Maybe making it aware that is is in a rejects state so it doesn't complain about not receiving a function somehow?

PR welcome!

Thanks @lsentkiewicz !

@lsentkiewicz
Hi I saw the pr is merge, but I still cannot match the Error with jest
Would you help me?

My test is here

describe('[Model] tag', () => {
  test('Error: empty parameter', async () => {
    expect.assertions(1);
    await expect(tagModel.create()).rejects.toMatchObject({
      message: 'tag'
    });
  });
});

And here is the function

  create(name) {
    if (_.isEmpty(name)) {
      throw new Error(`tag-model-1000`);
    }
    console.log('not here');
    return Tag.findOneAndUpdate({ name }, { updatedAt: new Date() }, {
      new: true, // If update will return new one rather than origin
      upsert: true, // If not exists then create
      setDefaultsOnInsert: true, // Set default value when create
    }).exists('deletedAt', false);
  }

screen shot 2017-12-05 at 22 32 48

I think the patch implements .rejects.toThrow(XXX) where XXX will match the message. (see https://github.com/facebook/jest/pull/4884). Not ideal (how can we match the actual error instance for example?) but already something.

EDIT: This was working on an older version doesn't seem to be working currently

I am really hopeful that this gets working the way it is listed in the docs because it is super intuitive and handy. In the meantime I like to do regex checks on my error messages so they are not too brittle this solution has worked for me

return expect(Promise.reject(new Error('octopus')))
  .rejects
  .toMatchObject({
    message: exepect.stringMatching(/oct/)
)}

Again hopeful for the doc implementation to work since it is less verbose

Is there any place in the docs where rejects.toMatchObject is? I can't find it.

You can open up a separate issue for it, the examples in the OP are fixed in Jest 22.

@SimenB just google jest toMatchObject

Spoiler, it will take you here: https://facebook.github.io/jest/docs/en/expect.html#tomatchobjectobject

I know where the docs for toMatchObject are, but none of the examples are with errors. I asked for rejects.toMatchObject.

I am really hopeful that this gets working the way it is listed in the docs because it is super intuitive and handy.

If it's just toMatchObject would be great to use with rejects then that's fine, but a separate feature request.

@simenB I discovered the chaining by going off of this statement in the docs about rejects

Use .rejects to unwrap the reason of a rejected promise so any other matcher can be chained. If the promise is fulfilled the assertion fails.

@SimenB maybe I just did something crazy wrong in my test but .rejects.toMatchObject() is working in my tests

Not asking for a feature just providing another work around.

This is still a problem.

Here is a reusable solution that can be used inside any async test/it function: a function called asyncThrowInJest to which you provide a promise value and an error message matcher:

test('Queue.submit throws task errors', async () => {
  const expected = 'bad'
  const errorMessageMatcher = new RegExp(`^${expected}$`)
  function task() {
    throw new Error(expected)
  }

  const e = new Queue()
  await asyncThrowInJest(e.submit(task), errorMessageMatcher)

  async function asyncThrowInJest(p, expectedErrorMessage) {
    let thrownError
    const v = await p.catch(e => thrownError = e)
    expect(() => {
      if (thrownError) throw thrownError
    }).toThrow(expectedErrorMessage)
    return v
  }
})

This is still a problem.

How so? Can you open up an issue?

@skbolton @SimenB The code snippet isn't working for me:

    it("foo", () => {
      return expect(Promise.reject(new Error("octopus"))).rejects.toMatchObject(
        {
          message: expect.stringMatching(/oct/),
        },
      );
    });

In fact it gives me the following error:


    expect(received).toMatchObject(expected)

    Expected value to match object:
      {"message": StringMatching /oct/}
    Received:
      [Error: octopus]
    Difference:
    - Expected
    + Received

      Object {
    -   "message": StringMatching /oct/,
    +   "message": "octopus",
      }

      at Object.<anonymous> (node_modules/expect/build/index.js:179:51)
          at Generator.throw (<anonymous>)
      at step (node_modules/expect/build/index.js:43:727)
      at node_modules/expect/build/index.js:43:926

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        3.533s, estimated 4s
Ran all test suites matching /user.test/i.

@alem0lars Sorry to get your hopes up. Maybe there has been a regression. I am running my tests on jest 20.0.4 I thought these tests were on a more current version. For what its worth though it was working then

@alem0lars that seems like a different issue, it doesn't work without rejects either. See https://repl.it/repls/JoyousImpressiveYeti.

Could you open up a new issue about toMatchObject not working to assert on the message of an error?

@SimenB done :)

Here is my solution:

test('addItem mutation rejects invalid user', async () => {
  try {
    await addItem(root, noArgs, invalidContext)
  } catch (e) {
    expect(e.message).toMatch('You must be authenticated to run this query.')
  }
})

It is essentially what @lachlanhunt posted.

If you simply execute the function under test with the arguments necessary to output the expected error, you can observe it in the catch block and do a simple string check.

@agm1984 your test will pass if addItem does not throw, unless you use expect.assertions : Documentation

As explained and based on the work here, I made a small function to help:

// My final utility function, "synchronizer":
const sync = fn => fn.then(res => () => res).catch(err => () => { throw err });

// Example function for testing purposes
const check = async arg => {
  if (arg > 5) throw new Error('Too large!');
  if (arg < 0) throw new Error('Too small!');
  return 'Good to go';
};

// Write the expect() in quite a clear way
it('checks the boundaries properly', async () => {
  expect(await sync(check(-1))).toThrow();  // Can also take 'Too small!' or /Too small!/
  expect(await sync(check(0))).not.toThrow();
  expect(await sync(check(5))).not.toThrow();
  expect(await sync(check(10))).toThrow();
});

It has the added benefit compared to rejects that if you forget either the await or the sync, it'll throw errors and not fail silently. Same as if you try to pass a non-promise.

These big threads like this are such a mess. Is the bug fixed? If it is could someone please provide a final working sample with/without await/async?

I'm mocking node-fetch using a mock in the __mocks__ dir. I have a test that verifies that node-fetch is mocked.

I'm using Promises and this simple bit of code is throwing an error on the new Error

    it('rejects if http call fails', (done) => {
      const msg = 'OMG EXPLOSIONS';
      const error = new Error(msg);
      fetch.mockRejectedValue(error);
      expect(
        getCmsThread({
          msgBody: { collectionGroupId: '1', id: '2', marketplace: 'abc', language: 'en', cmsPath: 'http://test.com' }
        })
      ).rejects.toThrow(msg);
    });

Docs: https://jestjs.io/docs/en/mock-function-api#mockfnmockrejectedvaluevalue

My test fails:

  ● API › getArticle › rejects if http call fails

    OMG EXPLOSIONS

       62 |     it('rejects if http call fails', (done) => {
       63 |       const msg = 'OMG EXPLOSIONS';
     > 64 |       const error = new Error(msg);

It seems that the instant that the new Error is called my test fails.

Am I using it wrong? Sure seems like I'm following the docs. I'll post a full sample if someone can figure out what I'm doing wrong.

"jest": "~23.3.0",

@jcollum try returning in front of your expect

it('rejects if http call fails', () => {
  const error = 'OMG EXPLOSIONS'
  fetch.mockRejectedValue(new Error(msg))

  return expect(
    getArticle({
      msgBody: { 
        collectionGroupId: '1',
        id: '2', 
        marketplace: 'abc',
        language: 'en', 
        cmsPath: 'http://test.com' 
    }
  })
).rejects.toThrow(msg)
})

If you don't return the expect when doing promises it doesn't resolve/ reject it for you

The example in the docs tells you to await or return: https://jestjs.io/docs/en/expect#rejects

Actually the issue was that the code under test didn't have a .catch -- added that in and it behaved normally.

Complete test:

    it('rejects gracefully if http call fails', (done) => {
      const msg = 'OMG EXPLOSIONS'; 
      fetch.mock.calls.length.should.equal(0);
      fetch.mockRejectedValueOnce(new Error(msg));

      getArticle({
        msgBody: { collectionGroupId: '1', id: '2', marketplace: 'abc', language: 'en', cmsPath: 'http://test.com' }
      })
        .then(() => {
          done(new Error('Then step should not be hit'));
        })
        .catch((err) => {
          fetch.mock.calls.length.should.equal(1);
          err.message.should.equal(msg);
          done();
        });
    });

It would read cleaner with .rejects.toThrow(msg) and without the done. But it works.

As long as you return or await the promise, you don't need done. This has been stated multiple times in this issue.

it('rejects gracefully if http call fails', async () => {
  const msg = 'OMG EXPLOSIONS';
  expect(fetch).toHaveBeenCalledTimes(0);
  fetch.mockRejectedValueOnce(new Error(msg));

  await expect(() =>
    getArticle({
      msgBody: {
        collectionGroupId: '1',
        id: '2',
        marketplace: 'abc',
        language: 'en',
        cmsPath: 'http://test.com'
      }
    })
  ).rejects.toThrow(msg);

  expect(fetch).toHaveBeenCalledTimes(1);
});

@SimenB You are certainly correct about not needing done if await or return is used, but unfortunately your example is broken.

In Jest 23.0.1:

expect(received).rejects.toThrow()

    received value must be a Promise.
    Received:
      function: [Function anonymous]

On the other hand, this works:

await getArticle({
      msgBody: {
        collectionGroupId: '1',
        id: '2',
        marketplace: 'abc',
        language: 'en',
        cmsPath: 'http://test.com'
      }
    })
    .then(anything => throw new Error("Should not come here."))
    .catch(e => expect(e).toEqual(new Error("OMG EXPLOSIONS")))

@jcollum the catch is needed because you are configuring a test dependency to return a rejected promise which causes your function under test to reject (1). You don't need the done and you can do rejects.toThrow() you just have to return the expectation and assert on it (2). Also controlling what something returns (1) and asserting it was called is probably unnecessary (deleted in my example).

it('rejects gracefully if http call fails', () => {
  const msg = 'OMG EXPLOSIONS';
  fetch.mockRejectedValueOnce(new Error(msg));  // (1)

  const promise = getArticle({
    msgBody: {
      collectionGroupId: '1',
      id: '2',
      marketplace: 'abc', 
      language: 'en', 
      cmsPath: 'http://test.com' 
    }
  });

  return expect(promise).rejects.toThrow(msg); // (2)
});

For the async awaiters around these parts you can achieve the same thing you just don't want the async function of the test to return a rejected promise or else jest will fail the test (1). We want to catch that it would fail and do an assertion that way the test still passes (2). When catching you are handling the error and a non reject promise is returned

it('rejects gracefully if http call fails', async () => {  // (1)
  const msg = 'OMG EXPLOSIONS';
  fetch.mockRejectedValueOnce(new Error(msg));

  await getArticle({
    msgBody: {
      collectionGroupId: '1',
      id: '2',
      marketplace: 'abc', 
      language: 'en', 
      cmsPath: 'http://test.com' 
    }
  })
  .catch(err => expect(err).toEqual(new Error(msg)); // (2)

  // since we caught and handled the error the async function will resolve happily and not
  // fail our test
});

Thanks for the input.

For anyone having trouble parsing the content of this thread, the following is how you do it:

await expect(repo.get(999)).rejects.toThrow(NotFoundException);

Here's how I'm dealing with this in the event that I want to assert on properties of the error:

const promise = systemUnderTest()

await expect(promise).rejects.toEqual(new Error('the expected message'))
await expect(promise).rejects.toMatchObject({
  some: 'expected property value'
})

For anyone looking for a simple, working example of the problem posed in the original post:

test('example', async () => {
  async function fn() {
    throw new Error('some error')
  }

  await expect(fn()).rejects.toThrow('some error')
})

This documentation example is still misleading (as mentioned above in 2017):

await expect(fetchData()).rejects.toMatch('error');

If fetchData() throws an Error, the toMatch fails because it expects a string:

expect(string)[.not].toMatch(expected)

string value must be a string.
Received:
  object: [Error: Failed to get message]

The example only works if the function throws a string instead of an Error, which is not a great assumption for the documentation to make.

What works is to replace toMatch with toThrow as mentioned above:

await expect(fn()).rejects.toThrow('some error')

@robertpenner your final example only tests whether an Error was thrown, but will match regardless of whether that error's message was some error or not:

const fn = () => Promise.reject('expected message')

await expect(fn()).rejects.toThrow('expected message') // matches
await expect(fn()).rejects.toThrow('wrong message') // matches, though it shouldn't

I believe the .toHaveProperty or .toMatchObject approaches are the best for this situation.

Was this page helpful?
0 / 5 - 0 ratings