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.

jest.fn().waitUntilCalledNTimes() Feature

See original GitHub issue

🚀 Feature Proposal

Add some kind to feature to jest to wait until a mock function has been called n times.

Motivation

We have an API that recursively sends periodic notifications to another service, we need to check that this works, we currently have a setTimeout wrapped in a promise to make the test wait for a period thats deffinetly longer than needed.

Example

test('some test', async () => {
  const someMock = jest.fn()

  await someMock.waitUntilCalledNTimes(n) // on the nth call, continue.

  expect(someOtherMock).hasBeenCalled()
})

Pitch

Why does this feature belong in the Jest core platform?

It would be an addition to the core jest mocking ability, allowing for dynamic tests ensuring that a function has to of been called n times before moving on to check for its asssertions

Im happy to give this ago myself, if its something thats wanted

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:1
  • Comments:19 (5 by maintainers)

github_iconTop GitHub Comments

8reactions
rickhanloniicommented, Dec 2, 2018

Yeah that makes sense @benjaminkay93

I think this makes more sense in userland, as you said, it’s pretty niche

Here’s an example of how you could implement, let me know what you think

import { someApiEndpoint } form '../api-manager'
import helper from '../helpers'

const createWaitableMock = () => {
  let resolve;
  let times;
  let calledCount = 0;
  const mock = jest.fn();
  mock.mockImplementation(() => {
    calledCount +=1;
    if (resolve && calledCount >= times) {
      resolve(); 
    }
  });

  
  mock.waitToHaveBeenCalled = t => {
    times = t;
    return new Promise(r => {
      resolve = r;
    })
  }

  return mock;
}

test('some api endpoint test', async () => {
  helper.sendPayload = createWaitableMock();

  const req = {body: [ 'some', 'array' ]}
  const response = someApiEndpoint(req)

  expect(response).toBe('Replay Started!')

  await helper.sendPayload.waitToHaveBeenCalled(2) // explicit number of calls to be made then continue with assertions

  expect(helper.sendPayload).toHaveBeenCalledTimes(2) // I know here redundant but in actual code we have many calls out to things that could be assert to of happened twice
})
7reactions
SimenBcommented, Nov 29, 2018
await waitForExpect(() => {
  expect(someMock).toHaveBeenCalledTimes(n);
});

https://www.npmjs.com/package/wait-for-expect

Is that enough?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Mock Functions - Jest
Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function...
Read more >
Mock Functions or Spies Demystified - How Does jest.fn() Work?
Mock functions, also known as spies, are special functions that allow us to track how a particular function is called by external code....
Read more >
Why isn't my jest mock function implementation being called?
When I check lambda1/index.js in the debugger getVehicleMetaKeysFromDeviceId() is a jest object but when it is called it doesn't use my mock ...
Read more >
Understanding Jest Mocks - Medium
Learn about the Jest Mock Function and the different strategies ... The simplest way to create a Mock Function instance is with jest.fn()...
Read more >
Mocking functions and modules with Jest - pawelgrzybek.com
Let's have a look at them all. Function mock using jest.fn(); Function mock using jest.spyOn(); Module mock using jest.mock() ...
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