DEV Community

Cover image for Jestip, clear mocks automatically
jean-smaug
jean-smaug

Posted on • Edited on • Originally published at maximeblanc.fr

3 1

Jestip, clear mocks automatically

Let's take the following code as example.

function functionYouNeedToMock(a, b) {
  return a + b
}

beforeEach(() => {
  jest.clearAllMocks()
})

functionYouNeedToMock = jest.fn()

it("should call function", () => {
  functionYouNeedToMock()
  expect(functionYouNeedToMock).toBeCalledTimes(1)
})

it("should call function", () => {
  functionYouNeedToMock()
  expect(functionYouNeedToMock).toBeCalledTimes(1)
})

It considers that you mocked a function and you want your tests to be independent. So you're using the jest.clearAllMocks() function to avoid undesired behaviours.

Did you know that you can activate the clearMocks option in the config in order to avoid calling jest.clearAllMocks() in each test suite ?

// jest.config.js

module.exports = {
  clearMocks: true,
}

Now you can write

function functionYouNeedToMock(a, b) {
  return a + b
}

functionYouNeedToMock = jest.fn()

it("should call function", () => {
  functionYouNeedToMock()
  expect(functionYouNeedToMock).toBeCalledTimes(1)
})

it("should call function", () => {
  functionYouNeedToMock()
  expect(functionYouNeedToMock).toBeCalledTimes(1)
})

Thanks for reading

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up