簡體   English   中英

用 mocha 和 chai 測試“投擲”

[英]Testing 'throw' with mocha and chai

在我的 function 中,我使用:

  if (apples === undefined) {
    throw new Error('Error');
  }

在我的測試中,我試圖通過以下方式確認這是有效的:

  it('throw an error if apples is undefined', function() {
    const input = undefined;
    const output = "Error";
    assert.throws(myFunc(input), output);
  });

但是我得到:

1 次失敗

  1. 如果 apples 未定義,myFunc 應該拋出一個錯誤:Error Error

這是因為assert.throws第一個參數采用 function定義,而不是 function結果 它調用傳遞的 function 本身。 在您的示例中,您調用的是 function 因此您傳遞的是 function 結果。

而不是這個:

assert.throws(myFunc(), output)

像這樣做:

assert.throws(myFunc, output)

If you want to pass parameters to the function under test, you'll need to wrap it in another unnamed function or use Function.bind to bind some arguments to it.

這是一個工作示例:

const assert = require("assert")

function myFunc(apples) {
  if (!apples) {
    throw new Error("Apples must have a non-null value");
  }

  return apples + " are good";
}


describe("myFunc", () => {
  it("throws an error if apples is undefined", function() {
    const input = undefined;
    const output = new Error("Error");

    assert.throws(function() {
      myFunc(input);
    }, output);
  })
})

請注意,您還需要測試它是否拋出了Error的實例而不是String

暫無
暫無

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

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