热门模拟具有不同类型返回值的函数?

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

我使用Jest在NodeJS上编写单元测试。有一种方法可以返回一个实体或一组实体。当我尝试模拟此方法的返回值时,我只能传递数组,但需要一个实体。

npm i jest typeorm

const manager = new EntityManager(null);
const sale = new Sale();
jest.spyOn(manager, 'create').mockReturnValue(sale);  

最后一个字符串会导致错误:Argument of type 'Sale' is not assignable to parameter of type '{}[]'. Type 'Sale' is missing the following properties from type '{}[]': length, pop, push, concat, and 26 more.

typescript jestjs
1个回答
0
投票

您可以使用withArgs实现此目的,

withArgs(参数... args)→

指定用于调用具有指定参数的spy的策略

例如:

spyOn(something, 'func').withArgs(arg1).returnValue(obj);

然后再次spyOn与不同的returnValue

spyOn(something, 'func').withArgs(arg2).returnValue(arrayValue);
© www.soinside.com 2019 - 2024. All rights reserved.