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

mvm*_*oay 36 javascript unit-testing mocha.js node.js

鉴于我有两个ES6课程.

这是A类:

import B from 'B';

class A {
    someFunction(){
        var dependency = new B();
        dependency.doSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

和B级:

class B{
    doSomething(){
        // does something
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用摩卡(用于ES6的babel),柴和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???
    });
});
Run Code Online (Sandbox Code Playgroud)

vic*_*ohl 34

您可以使用SinonJS创建存根以防止执行实际功能.

例如,给定A类:

import B from './b';

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

export default A;
Run Code Online (Sandbox Code Playgroud)

和B级:

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

export default B;
Run Code Online (Sandbox Code Playgroud)

测试看起来像:

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');
    });
});
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用object.method.restore();以下方法恢复该功能:

var stub = sinon.stub(object,"method");
用stub函数替换object.method.可以通过调用object.method.restore();(或stub.restore();)来恢复原始功能 .如果属性不是函数,则抛出异常,以帮助避免在存根方法时出现拼写错误.