为什么我在通过mochai和chai进行测试时没有通过投掷错误测试?

时间:2016-12-15 21:23:24

标签: javascript testing error-handling ecmascript-6 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)

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

1 个答案:

答案 0 :(得分:1)

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

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