簡體   English   中英

熱衷於模擬具有不同類型的返回值的函數嗎?

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

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

指定用於具有指定參數的間諜程序調用的策略

例如:

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

然后再次為不同的returnValue使用不同的spyOn

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM