如何使用mocha.js模拟单元测试的依赖类?

时间:2015-09-21 12:28:11

标签: javascript node.js unit-testing mocha

鉴于我有两个ES6课程。

这是A类:

import B from 'B';

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

B班:

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

我使用mocha进行单元测试(使用babel for ES6),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???
    });
});

1 个答案:

答案 0 :(得分:30)

您可以使用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;

测试看起来像:

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');
    });
});

然后,您可以根据需要使用object.method.restore();恢复该功能:

  

var stub = sinon.stub(object,“method”);
  用一个替换object.method   存根功能。可以通过调用恢复原始功能   object.method.restore();(或stub.restore();)。抛出异常   如果属性不是一个功能,以帮助避免拼写错误   存根方法。