为什么我在通过 mochai 和 chai 测试时没有通过 throwing-error 测试?

Why I failed the throwing-error test when testing via mochai and chai?

我想测试一个函数在某些情况下是否会抛出错误,但它总是测试失败(第一个),但是当我写一个简单的测试(第二个)时,它通过了,为什么?

要测试的函数

export function add(numbers){
    let nums = numbers.split(",")
    let temp = 0
    for (let num of nums) {
        num = parseInt(num)
        if (num < 0) {
            throw new Error("negative not allowed")
        }
        temp += num
    }
    return temp;
}

这是测试

import chai from "chai"
import {add} from "../try"

let expect = chai.expect
let should = chai.should()

describe("about the error throwing case", function(){
    it("should throw an error when get a negative number", function(){
        expect(add("-1,2,3")).to.throw("negative not allowed")
    })

    it("should pass the throw-error test", function(){
        (function(){throw new Error("i am an error")}).should.throw("i am an error")
        expect(function(){throw new Error("i am an error")}).to.throw("i am an error")    
    })
})

结果

./node_modules/mocha/bin/mocha test/testtry.js --require babel-register -u tdd --reporter spec



  about the error throwing case
    1) should throw an error when get a negative number
    ✓ should pass the throw-error test


  1 passing (18ms)
  1 failing

  1) about the error throwing case should throw an error when get a negative number:
     Error: negative not allowed
      at add (try.js:7:19)
      at Context.<anonymous> (test/testtry.js:9:16)

为什么以及如何解决?谢谢

您应该将函数传递给 expect(),而不是函数调用:

expect(function() {add("-1,2,3")}).to.throw("negative not allowed")