2016-12-15 78 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") 
相關問題