【问题标题】:Sinon Stub the whole class诗乃 Stub 全班
【发布时间】:2020-08-06 10:03:50
【问题描述】:

我在A.js 文件中有以下类,

class A {
    constructor(name) {
        this.name = name;
    }

    getResult() {
        return this.name;
    }
}

module.exports = A

在另一个名为controller.js的文件中,我是这样使用的,

const A = require('./A');

module.exports = {
    doProcess: () => {
        const a = new A('John');

        console.log(a.getResult());
    }
}

所以我的要求是,我想在为controller.js 编写单元测试时对类 A 及其方法进行存根。如何使用 sinon 实现这一点?

类似的,

const getResultStub = sinon.stub();
getResultStub().returns('success');

【问题讨论】:

  • Factory 模式呢?您可以在控制器和以后的模拟中使用它。

标签: javascript unit-testing sinon


【解决方案1】:

如果是默认导出,我不相信你可以直接stub它。

如果您在 nodejs 环境中工作,您可以使用proxyquire,或者执行以下操作:

// A.js

class A {
    constructor(name) {
        this.name = name;
    }

    getResult() {
        return this.name;
    }
}

module.exports = A
// controller.spec.js

const sinon = require('sinon')

class DummyA {
  constructor(){}
  getResult(){
    return 'success'
  }
}

require.cache[require.resolve('./A')] = DummyA

const controller = require('./controller.js')

【讨论】:

  • 我可以使用 proxyquire,但您能建议使用它的解决方案吗?
  • 您的意思是没有proxyrequire 的解决方案?请注意,我不是nodejs专家,但这里是我的理解:当noderequire一个模块时,它会首先通过运行require.resolve来确定模块的绝对路径,然后检查它是否已经在@中被需要987654328@字典。
  • (顺便说一句,你可以做console.log(require.resolve('./A'))并检查输出)
  • other 方法有效地填充了./A 模块在require.cache 字典中
  • 顺便说一句,我想我引用了错误的包...它可能是 proxyquire 而不是
猜你喜欢
  • 1970-01-01
  • 2015-07-15
  • 1970-01-01
  • 2016-08-04
  • 2019-07-07
  • 2017-05-12
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
相关资源
最近更新 更多