Jest: Add .mockThrowValue and .mockThrowValueOnce

Created on 6 Feb 2019  路  4Comments  路  Source: facebook/jest

馃殌 Feature Proposal

Add .mockThrowValue and .mockThrowValueOnce

Motivation

We have .mockResolvedValue and .mockRejectedValue, but there is no parity for .mockReturnValue.

The current alternative is to use

.mockImplementation(() => {
  throw new Error('some error');
});

This can be simplified to

.mockThrowValue(new Error('some error'));

Pitch

A similar feature request was rejected: https://github.com/facebook/jest/issues/2160

I believe that feature request wasn't good enough to be added to core because in Javascript you can throw anything.

I see .mockImplementation as a catch all for the general case, but mocking thrown errors should be a common case when unit testing. By adding .mockThrowValue to core we can continue to see .mockImplementation as "requires special attention" when doing code reviews.

Feature Request Help Wanted

All 4 comments

Related: #6180. I think we'll want to at least explore that more before expanding the current API. Thoughts on the API and capabilities suggested there?

I think #6180 is a great addition, but I don't believe it ought to replace the existing one. I think both have their merits and we should add mockThrowValue.

@SimenB while I think #6180 is a very cool proposal, I also think there's value in having parity w/ .mockReturnValue given mockResolvedValue & mockRejectedValue.

Would you accept a PR for this?

Would you accept a PR for this?

Yes 馃檪

Was this page helpful?
0 / 5 - 0 ratings