jest: rejects.toThrowError

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

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 35
  • Comments: 54 (15 by maintainers)

Commits related to this issue

Most upvoted comments

+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.

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

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.

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

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

image

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.

@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';
}

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

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.

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')

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

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

To test multiple properties, the following is working:

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

@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

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

@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.

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

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

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.

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

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.

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?

+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”)

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

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