带有expect的mocha不适用于测试错误

mocha with expect is not working for testing errors

本文关键字:适用于 测试 错误 不适用 mocha expect 带有      更新时间:2023-12-08

在下面的脚本中,只有一个测试通过。测试错误(throw error())失败,返回消息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);

如果你用节点的方式进行错误优先回调,它看起来更像这样:

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');
  });
});