简体   繁体   English

用 mocha 和 chai 测试“投掷”

[英]Testing 'throw' with mocha and chai

In my function I use:在我的 function 中,我使用:

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

In my test I am trying to confirm this is working by doing:在我的测试中,我试图通过以下方式确认这是有效的:

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

However I get:但是我得到:

1 failing 1 次失败

  1. myFunc should throw an error if apples is undefined: Error Error如果 apples 未定义,myFunc 应该抛出一个错误:Error Error

That's because assert.throws 1st parameter takes the function definition , not the function result .这是因为assert.throws第一个参数采用 function定义,而不是 function结果 It calls the passed function itself.它调用传递的 function 本身。 In your example, you're calling the function therefore you're passing the function result.在您的示例中,您调用的是 function 因此您传递的是 function 结果。

Instead of this:而不是这个:

assert.throws(myFunc(), output)

Do it like this:像这样做:

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. 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.

Here's a working example:这是一个工作示例:

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);
  })
})

Note that you also need to test that it throws an instance of an Error instead of a String .请注意,您还需要测试它是否抛出了Error的实例而不是String

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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