【问题标题】:Why I failed the throwing-error test when testing via mochai and chai? [duplicate]为什么我在通过 mochai 和 chai 测试时抛出错误测试失败? [复制]
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多