使用本机节点测试库模拟不同的调用

问题描述 投票:0回答:1

我正在迁移项目以使用本机节点测试运行器和模拟库。以前我用过

sinon

import { stub } from "sinon"

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

functionWhichExecutesMyStubThreeTimes()

如何使用节点实现相同的效果?我尝试了以下方法;

import { mock } from "node:test"

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

functionWhichExecutesMyMockThreeTimes()

这行不通。

mockImplementationOnce
的文档显示了使用模拟实现、调用它,然后根据需要再次模拟它以再次运行的基本示例。

我无法执行此操作,因为我的用例中的实现在“黑盒”函数中进行了三个调用

functionWhichExecutesMyMockThreeTimes
。因此,我需要模拟不同的实例并仅运行模拟触发函数一次。

node.js testing mocking
1个回答
0
投票

我没有足够仔细地阅读类型签名;

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()
© www.soinside.com 2019 - 2024. All rights reserved.