-
-
Notifications
You must be signed in to change notification settings - Fork 6.6k
Closed
Labels
Description
π Feature Proposal
Today exists the method .mockRejectedValue[Once]
where we can return the failed async value on Jest.Mocked but doesn't exists an equivalent way on sync methods. the unique way is using a mockImplementation[Once] like:
it('example', () => {
const fn = jest.fn().mockImplementation/* Once */(()=> {
throw new Error() // any formatter will force code like this
})
})
There should be a method like .mockThrowValue[Once]
:
it('example', () => {
// as wrapper for .mockImplementation[Once] passing throw value
const fn = jest.fn().mockThrowValue/* Once */(new Error())
})
The implementation is simple:
Object.defineProperty(jest.fn().constructor.prototype, 'mockThrowValue', {
value: function(error) {
return this.mockImplementation(() => {
throw error;
});
},
writable: true,
configurable: true,
});
Object.defineProperty(jest.fn().constructor.prototype, 'mockThrowValueOnce', {
value: function(error) {
return this.mockImplementationOnce(() => {
throw error;
});
},
writable: true,
configurable: true,
});
Motivation
Write cleaner code using sync methods
Example
// current way
const fn = jest.fn().mockImplementation/* Once */(() => { throw new Error() })
// new way (more clean)
const fn = jest.fn().mockThrowValue/* Once */(new Error())
Pitch
Because exists the same structure for async methods called .mockRejectedValue[Once]()