简体   繁体   中英

Hot to mock functions with different types of return values?

I use Jest for writing unit-tests on 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.

You can use withArgs to achieve this,

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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