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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了热门模拟具有不同类型返回值的函数?相关的知识,希望对你有一定的参考价值。

我使用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.

答案

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

withArgs(参数... args)→

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

例如:

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

然后再次spyOn与不同的returnValue

spyOn(something, 'func').withArgs(arg2).returnValue(arrayValue);

以上是关于热门模拟具有不同类型返回值的函数?的主要内容,如果未能解决你的问题,请参考以下文章