即使调用构造函数,Sinon.js监视类构造函数也会返回false

时间:2017-11-04 11:08:24

标签: node.js sinon chai

我是第一次尝试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包含错误对象,我的测试也会失败。

1 个答案:

答案 0 :(得分:0)

constructor无法对课程Sinon进行存档。

来自Sinon项目的维护者:

  

ES6类中的构造函数关键字只是语法糖。您仍然需要实际测试创建类的函数的调用,而不是其构造函数属性。

链接:https://github.com/sinonjs/sinon/issues/831#issuecomment-209648966

相关问题