![](/img/trans.png)
[英]Jest unit testing a function that calls a function returning a Promise
[英]Jest Unit Testing function that calls a second one that returns a promise
應用了 vazsonyidl 建議的已編輯問題
我必須為類似於此的 function 編寫單元測試:
import {External} from 'ExternalModule';
async functionA(){
this.functionB().then((data) => {
External.functionC(options);
console.log("Reached1");
}).catch((data) => {
const { OnError = "" } = data || {}
if(OnError) {
External.functionC(anotherOptions);
console.log("Reached2");
}
})
}
functionB() {
return new Promise(() => {
});
}
由於 functionC 屬於另一個模塊,我將它的模擬放在_mocks_
文件夾中:
//_mocks_/ExternalModule.ts
export var External: ExternalClass = {
functionC(){}
}
class ExternalClass{
constructor(){};
functionC(){};
}
我以兩種不同的方式模擬了 functionB 來測試then
和catch
:
it("should test then block", () => {
functionB = jest.fn(() => {return Promise.resolve()});
const functionSpy = jest.spyOn(ExternalModule.External, 'functionC');
void functionA().then(() => {
expect(functionSpy).not.toHaveBeenCalled();
});
})
it("should test catch block", () => {
const err = { OnError: "Error" };
functionB = jest.fn(() => {return Promise.reject(err)});
const functionSpy = jest.spyOn(ExternalModule.External, 'functionC');
void functionA().then(() => {
expect(functionSpy).not.toHaveBeenCalled();
});
})
我想要做的是期望 functionC 被調用並使用正確的參數調用,但是即使我測試 functionC 是否沒有被調用,測試也總是通過。
我究竟做錯了什么?
我認為當這個 function 捕獲錯誤時,這個錯誤應該有一個 'OnError' 屬性,以便函數 C 可以運行。
const { OnError = "" } = data || {}
if(OnError) {
ExternalClass.functionC(anotherOptions);
}
更改您的響應錯誤數據以return Promise.reject({OnError: '404'})
可能會解決此問題。
因為您沒有將它提供給您的 class。 以下代碼對我有用:
class A { async functionA() { this.functionB().then((data) => { this.functionC(); // It woll log aaa here, you need this one. }).catch((data) => { const {OnError = ''} = data || {}; if (OnError) { console.log('onerror'); } }); } functionB() { return new Promise(() => { }); } functionC() { return 2; } } describe('a', () => { it('test', () => { const a = new A(); a.functionB = jest.fn(() => Promise.resolve()); const functionBSpy = jest.spyOn(a, 'functionC'); void a.functionA().then(() => { expect(functionBSpy).toHaveBeenCalledTimes(1); }); }); });
希望這會有所幫助,任何評論表示贊賞。
由於您沒有提供有關您的功能 B 的信息,我嘲笑了一些可能適合您的東西。
您最初的問題是 Jest 不會等待您的回調解決。 盡管它會進行斷言,但即使您的 function 調用稍后發生,Jest 也不會識別它們並說從未發生過調用。
有幾個可用的文檔,例如 Jest's one here
Jest 在進行斷言之前不會等待異步代碼完成。
您可以使用以下 function:
const waitForPromises = () => new Promise(setImmediate);
強制 Jest 在繼續之前等待承諾完成:
it("does something", async () => {
promiseCall();
await waitForPromises();
expect(something).toBe(something)
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.