【问题标题】:Why do functions that throw exception not pass with function_name.should.throw(error)?为什么抛出异常的函数不通过 function_name.should.throw(error) 传递?
【发布时间】:2017-08-01 00:45:45
【问题描述】:

我们有以下工作测试示例:

"use strict";

var should = require("chai").should();

var multiply = function(x, y) {
  if (typeof x !== "number" || typeof y !== "number") {
    throw new Error("x or y is not a number.");
  }
  else return x * y;
};

describe("Multiply", function() {
  it("should multiply properly when passed numbers", function() {
    multiply(2, 4).should.equal(8);
  });

  it("should throw when not passed numbers", function() {
    (function() {
      multiply(2, "4");
    }).should.throw(Error);
  });
});

没有解释为什么需要使用 hack 运行第二个测试

(function() {
      multiply(2, "4");
    }).should.throw(Error);

如果你像这样运行它

it("should throw when not passed numbers", function() {
      multiply(2, "4").should.throw(Error);
  });

测试失败

  Multiply
    ✓ should multiply properly when passed numbers
    1) should throw when not passed numbers

但将函数作为常规节点脚本运行确实会失败:

Error: x or y is not a number.
    at multiply (/path/test/test.js:7:11)

所以我不明白为什么 should 没有发现它抛出错误的事实。

需要在匿名function() { } 调用中包装它的原因是什么?它是用于异步运行的测试,还是范围或其他什么?

【问题讨论】:

    标签: javascript unit-testing mocha.js chai


    【解决方案1】:

    Chai 是普通的 JavaScript,而不是魔法。如果你有一个表达式 a().b.c()a throws,c() 无法捕捉到它。 c 甚至无法运行。引擎甚至不知道c 是什么,因为a 没有返回一个可以查找.b.c 的值;相反,它抛出了一个错误。当您使用函数时,您有一个可以在其上查找.should 的对象,这反过来又为您提供了一个可以在其上查找和调用.throw 的对象。

    这就是它不能这样做的原因,但从 API 的角度来看,并没有错:.should.throw 只是对函数的断言,而不是函数调用。

    我还建议使用 Chai 的 expect,它不会将自身插入到 Object.prototype 中以呈现魔法的外观。

    【讨论】:

      猜你喜欢
      • 2011-12-12
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多