Parameterised mock return values
See original GitHub issue🚀 Feature Proposal
Add .when
/.thenReturn
support to the Jest mock API.
when
: Takes arguments to match the mock call against.
thenReturn
: Takes a vale to return when the when
clause matches a given call.
Motivation
This behaviour exists in mocking libraries from other languages see Mockito
This API will allow more expressive mocks, extending on top of the idea of mockReturnValue
and mockReturnValueOnce
.
Example
test('Mock when(x).thenReturn(y)', () => {
const mock = jest.fn()
.when(1) // one primitive argument
.thenReturn(2)
.when(3, 4) // multiple primitive arguments
.thenReturn(7)
.when('id')
.thenReturn(a => a) // return a function
.when({ hello: 'world' }) // object argument
.thenReturn('Hello, world!');
expect(mock(1)).toBe(2);
expect(mock(3, 4)).toBe(7);
expect(mock('id')('Awesome Jest')).toBe('Awesome Jest');
expect(mock({ hello: 'world' })).toBe('Hello, world!');
});
The API in Mockito also offers argument matchers for given types and custom equality checkers i.e.
test('returns jest-cool when given a number)', () => {
const mock = jest.fn()
.when(any(Number))
.thenReturn('jest-cool');
expect(mock(1)).toBe('jest-cool');
expect(mock(2)).toBe('jest-cool');
expect(mock(3)).toBe('jest-cool');
});
test('returns 🍌 when given odd numbers)', () => {
const isOdd = n => n % 2 != 0;
const mock = jest.fn()
.when(isOdd)
.thenReturn('🍌');
expect(mock(1)).toBe('🍌');
expect(mock(3)).toBe('🍌');
expect(mock(5)).toBe('🍌');
});
Pitch
Why in Core?
This could go in user land but the API would suffer for it! It would be more verbose and would not be able to bind to the mock. Instead it would have to mutate Jest’s mock API which would likely discourage people from using it.
My Questions
What should happen if a mock call value doesn’t match any when
clauses?
- Should the test fail?
- Return
undefined
? - Return the original mock implementation?
cc/ @SimenB @rickhanlonii @cpojer
I’m happy to start on a PR for this if you guys are happy adding it to core 😄
Issue Analytics
- State:
- Created 5 years ago
- Reactions:278
- Comments:29 (5 by maintainers)
Top GitHub Comments
Bumping this thread, I feel this should be in the core
Anyone currently working on it? If not, I’d love to take a shot with a PR. Been using Mockito on Java for long and recently started using jest and I’m really missing this.