2016-12-15 56 views
0

我想测试某个函数在面对某些情况时是否可以抛出错误,但它总是失败(第一个),但是当我编写一个简单测试(第二个)时,它通过了,为什么?为什么我在通过mochai和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

你应该通过一个函数来expect(),而不是一个函数调用:

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