我是第一次尝试sinon.js,这是我正在尝试测试的一段代码:
class ErrorWithStatusCode extends Error{
constructor(code, message, err){
super(message);
this.code = code;
this.error = err;
}
}
export {ErrorWithStatusCode}
这是我的测试文件
import {ErrorWithStatusCode} from '../../handlers/error.handler';
import chai from 'chai';
import sinon from 'sinon';
const should = chai.should();
const expect = chai.expect;
describe('Error Class', ()=>{
it('the contructor function should be called once', ()=>{
const spyFunc = sinon.spy(ErrorWithStatusCode, 'constructor');
const err = new ErrorWithStatusCode(500, 'Sorry, some error occurred.', {message: 'Some error'});
console.log(err);
expect(spyFunc.calledOnce).to.be.true;
})
});
但是,我的测试失败了,即使err
包含错误对象。
在
Sinon
中无法存根类constructor
。
来自Sinon
项目的维护者:
ES6 类中的构造函数关键字只是语法糖。您仍然需要实际测试创建类的函数的调用,而不是其构造函数属性。
链接: https://github.com/sinonjs/sinon/issues/831#issuecomment-209648966