【问题标题】:How to mock dependency classes for unit testing with mocha.js?如何使用 mocha.js 模拟用于单元测试的依赖类?
【发布时间】:2015-12-18 03:42:32
【问题描述】:

鉴于我有两个 ES6 类。

这是A类:

import B from 'B';

class A {
    someFunction(){
        var dependency = new B();
        dependency.doSomething();
    }
}

B 类:

class B{
    doSomething(){
        // does something
    }
}

我正在使用 mocha(对于 ES6 使用 babel)、chai 和 sinon 进行单元测试,效果非常好。但是在测试 A 类时如何为 B 类提供模拟类呢?

我想模拟整个 B 类(或所需的函数,实际上并不重要),这样 A 类就不会执行真正的代码,但我可以提供测试功能。

这就是 mocha 测试现在的样子:

var A = require('path/to/A.js');

describe("Class A", () => {

    var InstanceOfA;

    beforeEach(() => {
        InstanceOfA = new A();
    });

    it('should call B', () => {
        InstanceOfA.someFunction();
        // How to test A.someFunction() without relying on B???
    });
});

【问题讨论】:

  • 阅读DI

标签: javascript node.js unit-testing mocha.js


【解决方案1】:

你可以使用SinonJS创建一个stub来防止真正的函数被执行。

例如,给定A类:

import B from './b';

class A {
    someFunction(){
        var dependency = new B();
        return dependency.doSomething();
    }
}

export default A;

B 类:

class B {
    doSomething(){
        return 'real';
    }
}

export default B;

测试可能如下所示:(sinon )

describe("Class A", () => {

    var InstanceOfA;

    beforeEach(() => {
        InstanceOfA = new A();
    });

    it('should call B', () => {
        sinon.stub(B.prototype, 'doSomething', () => 'mock');
        let res = InstanceOfA.someFunction();

        sinon.assert.calledOnce(B.prototype.doSomething);
        res.should.equal('mock');
    });
});

编辑:对于 sinon 版本 >= v3.0.0,使用这个:

describe("Class A", () => {

    var InstanceOfA;

    beforeEach(() => {
        InstanceOfA = new A();
    });

    it('should call B', () => {
        sinon.stub(B.prototype, 'doSomething').callsFake(() => 'mock');
        let res = InstanceOfA.someFunction();

        sinon.assert.calledOnce(B.prototype.doSomething);
        res.should.equal('mock');
    });
});

如果需要,您可以使用object.method.restore(); 恢复该功能:

var stub = sinon.stub(object, "method");
将 object.method 替换为 存根函数。调用可以恢复原来的功能 object.method.restore();(或stub.restore();)。抛出异常 如果该属性还不是一个函数,以帮助避免输入错误 存根方法。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-02-19
  • 2015-02-04
  • 2015-07-14
  • 2019-12-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2012-07-11
相关资源
最近更新 更多