带有 expect 的 mocha 不适用于测试错误
mocha with expect is not working for testing errors
在下面的脚本中只有一个测试通过。测试错误(抛出错误())失败并显示消息
1) 测试应该抛出错误:
var expect = require('chai').expect;
describe("a test", function() {
var fn;
before(function() {
fn = function(arg){
if(arg == 'error'){
throw new Error();
}else{
return 'hi';
}
}
});
it("should throw error", function() {
expect(fn('error')).to.throw(Error);
});
it("should return hi", function() {
expect(fn('hi')).to.equal('hi');
});
});
如何修改期望测试错误?
expect()
需要一个函数来调用,而不是函数的结果。
将您的代码更改为:
expect(function(){ fn("error"); }).to.throw(Error);
如果你以 Node 方式使用错误优先回调,它看起来更像这样:
var expect = require('chai').expect;
describe("a test", function() {
var fn;
before(function() {
fn = function(err, callback){
if(err) throw new Error('failure');
return callback();
}
});
it("should throw error", function() {
expect(fn('error')).to.throw(Error);
});
it("should return hi", function() {
var callback = function() { return 'hi' };
expect(fn(null, callback).to.equal('hi');
});
});
在下面的脚本中只有一个测试通过。测试错误(抛出错误())失败并显示消息 1) 测试应该抛出错误:
var expect = require('chai').expect;
describe("a test", function() {
var fn;
before(function() {
fn = function(arg){
if(arg == 'error'){
throw new Error();
}else{
return 'hi';
}
}
});
it("should throw error", function() {
expect(fn('error')).to.throw(Error);
});
it("should return hi", function() {
expect(fn('hi')).to.equal('hi');
});
});
如何修改期望测试错误?
expect()
需要一个函数来调用,而不是函数的结果。
将您的代码更改为:
expect(function(){ fn("error"); }).to.throw(Error);
如果你以 Node 方式使用错误优先回调,它看起来更像这样:
var expect = require('chai').expect;
describe("a test", function() {
var fn;
before(function() {
fn = function(err, callback){
if(err) throw new Error('failure');
return callback();
}
});
it("should throw error", function() {
expect(fn('error')).to.throw(Error);
});
it("should return hi", function() {
var callback = function() { return 'hi' };
expect(fn(null, callback).to.equal('hi');
});
});