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

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay