用mocha测试json.parse

时间:2012-09-30 13:45:13

标签: javascript node.js mocha

为什么在使用mocha进行测试时,以下代码未通过?

我的示例模块:

module.exports = function(){
  JSON.parse("this is not json")
}

和我的test.js:

var should = require("should")
var module = require("./module")

describe("error testing", function(){
  it("should throw an error", function(done){
    module().should.throw();
    done();
  })
})

我希望测试通过,但运行mocha会给我以下内容:

✖ 1 of 1 tests failed:

1) error testing should throw an error:
   SyntaxError: Unexpected token h
    at Object.parse (native)
    at module.js:9:8
    at Context.<anonymous> (test.js:6:5)
    at Test.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:145:15)
    at Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:270:10)
    at /usr/local/lib/node_modules/mocha/lib/runner.js:314:12
    at next (/usr/local/lib/node_modules/mocha/lib/runner.js:198:14)
    at /usr/local/lib/node_modules/mocha/lib/runner.js:207:7
    at next (/usr/local/lib/node_modules/mocha/lib/runner.js:157:23)
    at Array.0 (/usr/local/lib/node_modules/mocha/lib/runner.js:175:5)
    at EventEmitter._tickCallback (node.js:192:40)

1 个答案:

答案 0 :(得分:1)

should.throw()期望在函数上调用,而不是函数的结果。改变这个:

module().should.throw();

到此:

module.should.throw();