簡體   English   中英

期望一個函數在 Jest 中拋出異常

[英]Expect a function to throw an exception in Jest

我有一個返回承諾的函數( hostelService.book ): return Promise.resolve(response); 我做了這個測試:

const action = async () => {
        await hostelService.book(id);
    };


  await expect(action).rejects.toThrow();

但我有這個錯誤:

 Matcher error: received value must be a promise

Jest 拋出此錯誤Matcher error: received value must be a promise因為在expect您只是傳遞函數引用。 沒有() - action只是一個函數引用,它不會返回任何東西。

要解決此問題,您必須像action()一樣在 expect 中調用該函數,以便它返回 promise 對象。

第二部分,你必須拋出錯誤。 Promise.reject(new Error('some error')); 在拒絕中,因此可以完全填充tothrow條件。

例子:

function hostelService() {
   return Promise.reject(new Error('some error'));
}

const action = async () => {
   await hostelService();
};

it( "Should throw the error", async () => {
   await expect(action()).rejects.toThrow('some error');
});

希望這會有所幫助。

您的測試失敗,因為您正在等待承諾(因此,當您對其調用.rejects時,它不再是 Promise)。 如果您從最后一個語句中刪除await ,它應該可以解決問題:

const action = async () => {
  await hostelService.book(id);
};

expect(action()).rejects.toThrow();

這是其背后的一些基本原理。 async自動將您的返回類型包裝到一個 Promise 中。 但是,當您調用await ,它會同步“解開”給定 Promise 的值,因此它無法對結果調用.rejects (除非您將一個 Promise 包裝到另一個 Promise 中)。

我編寫了一個小例子來說明我的意思。

看起來你幾乎擁有它。 我創建了一個帶有拋出錯誤和通過測試的函數的代碼沙盒。 您可以在代碼沙盒內的終端中使用npm run test運行它。 這是鏈接:

https://codesandbox.io/s/musing-goodall-ssss4?fontsize=14&hidenavigation=1&theme=dark

但基本上代碼是這樣的:

const action = async () => {
  throw new Error("error!")
}

describe("func", () => {
  it("should fail", async () => {
    await expect(action()).rejects.toThrow()
  })
})

與您顯示的代碼的不同之處在於缺少action()中的調用,這可能是類型錯誤。 我不知道這是否是一個錯誤,或者這不僅僅是代碼,而您只是想解釋您想要什么。 將來,為了更好地理解並幫助您未來的“幫手”,您應該發布您的代碼片段(或修改以避免屬性問題)。

這里的動作是函數,你不是從期望中調用它的。 我還從最后一行中刪除了 await

試試這個解決方案

const action = async () => {
  await hostelService.book(id);
};
expect(action()).rejects.toThrow();

不幸的是,您不能直接使用toThrow()測試拒絕。 拒絕它自己是一個錯誤對象,因此您可以測試是否相等。

test('', () => {
  // dont forget to call the action. 
  await expect(action()).rejects.toEqual(new Error())
});

您可以在此處找到更多解決方法https://github.com/facebook/jest/issues/1700

暫無
暫無

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

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