简体   繁体   English

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

[英]Hot to mock functions with different types of return values?

I use Jest for writing unit-tests on NodeJS. 我使用Jest在NodeJS上编写单元测试。 There is a method which can return one entity or array of entities. 有一种方法可以返回一个实体或实体数组。 When I try to mock returned value of this method I just can pass array, but need one entity. 当我尝试模拟此方法的返回值时,我只能传递数组,但需要一个实体。

npm i jest typeorm

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

Last string causes error: 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. 最后一个字符串导致错误: 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. 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.

You can use withArgs to achieve this, 您可以使用withArgs实现此目的,

withArgs(…args) → withArgs(…args)→

Specifies a strategy to be used for calls to the spy that have the specified arguments 指定用于具有指定参数的间谍程序调用的策略

Eg: 例如:

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

Then again spyOn with different for different returnValue 然后再次为不同的returnValue使用不同的spyOn

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM