question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

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:open
  • Created 5 years ago
  • Reactions:278
  • Comments:29 (5 by maintainers)

github_iconTop GitHub Comments

78reactions
Syttencommented, Apr 4, 2020

Bumping this thread, I feel this should be in the core

36reactions
nirgacommented, Jan 12, 2021

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Returning value that was passed into a method - Stack Overflow
I want to mock this with MOQ, so that it returns whatever was passed in - something like: _mock.Setup( theObject => theObject.DoSomething( It.IsAny<string>(...
Read more >
Change a Function's Output Based on Input Parameter Value ...
The way that we can “simulate” this behavior is to mock the function so that it actually doesn't extend beyond the software and...
Read more >
unittest.mock — mock object library — Python 3.11.1 ...
return_value: The value returned when the mock is called. By default this is a new Mock (created on first access). See the return_value...
Read more >
Setting Up Mock ref Return Values in Moq - Don't Code Tired
In the following test the Callback method is used to set the ref value. To be able to do this, a delegate must...
Read more >
Generate Return Values Using Lambdas in Moq - BlackWasp
Mock objects and stubs created using the Moq framework are generally used to inject dependencies with expectations that define fixed results ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found