Mocking on different calls with native node test library

109 Views Asked by At

I am migrating projects to use the native node test runner and mocking libraries. Previously I used sinon.

import { stub } from "sinon"

const myStub = stub()
  .onFirstCall().returns(1)
  .onFirstCall().returns(2)
  .onFirstCall().returns(3)

functionWhichExecutesMyStubThreeTimes()

How can I achieve the same with node? I tried the following;

import { mock } from "node:test"

const myMock = mock.fn().mock
myMock.mockImplementationOnce(() => 1)
myMock.mockImplementationOnce(() => 2)
myMock.mockImplementationOnce(() => 3)

functionWhichExecutesMyMockThreeTimes()

This doesn't work. The documentation for mockImplementationOnce shows a basic example of using mocking the implementation, calling it, then mocking it again as desired to run again.

I cannot do this as the implementation in my use case makes three calls within a 'black box' function functionWhichExecutesMyMockThreeTimes. As such, I need to mock the different instances and run the mocks triggering function only once.

1

There are 1 best solutions below

0
myol On BEST ANSWER

I didn't read the type signature close enough;

mockImplementationOnce(implementation: Function, onCall?: number): void;
import { mock } from "node:test"

const myMock = mock.fn().mock
myMock.mockImplementationOnce(() => 1, 0)
myMock.mockImplementationOnce(() => 2, 1)
myMock.mockImplementationOnce(() => 3, 2)

functionWhichExecutesMyMockThreeTimes()