【发布时间】:2016-12-15 21:23:24
【问题描述】:
我想测试一个函数在遇到某些情况时是否会抛出错误,但是它总是测试失败(第一个),但是当我写一个简单的测试(第二个)时,它通过了,为什么?
要测试的功能
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)
为什么以及如何解决它?谢谢
【问题讨论】:
标签: javascript testing error-handling ecmascript-6 chai