Skip to content

[Feature]: mockThrowValue[Once] (like mockRejectedValue[Once] but sync)Β #15752

@leandroluk

Description

@leandroluk

πŸš€ 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]()

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions