【问题标题】:Sinon.js spy on a class constructor returns false, even though the constructor is calledSinon.js 监视类构造函数返回 false,即使构造函数被调用
【发布时间】:2017-11-04 11:08:23
【问题描述】:

我是第一次尝试 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 包含错误对象。

【问题讨论】:

  • 不太确定这个测试试图完成什么?看起来您正在尝试验证您调用了刚刚模拟的函数?您不需要模拟构造函数;调用它并检查返回的对象是否设置了您作为参数传入的属性。

标签: node.js sinon chai


【解决方案1】:

Sinon 中无法对类constructor 进行存根。

来自Sinon 项目的维护者:

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


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

【讨论】:

    猜你喜欢
    • 2011-08-20
    • 1970-01-01
    • 2013-10-03
    • 2012-03-09
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    相关资源
    最近更新 更多