I want to test whether a function could throw an error when facing some cases, but it always failed the test(the 1st one), but when I wrote a single simple test (the 2nd one), it passed, why?
function to test
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;
}
this is the test
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")
})
})
results
./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)
Why and how to solve it? Thanks