如何使用mocha.js模拟单元测试的依赖类? [英] How to mock dependency classes for unit testing with mocha.js?

查看:82
本文介绍了如何使用mocha.js模拟单元测试的依赖类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我有两个ES6课程。

Given that I have two ES6 classes.

这是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类提供一个模拟类?

I am unit testing using mocha (with babel for ES6), chai and sinon, which works really great. But how can I provide a mock class for class B when testing class A?

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

I want to mock the entire class B (or the needed function, doesn't actually matter) so that class A doesn't execute real code but I can provide testing functionality.

这就是现在的mocha测试:

This is, what the mocha test looks like for now:

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


推荐答案

您可以使用SinonJS创建stub 以防止执行实际功能。

You can use SinonJS to create a stub to prevent the real function to be executed.

例如,给定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恢复该功能( );

You can then restore the function if necessary using object.method.restore();:


var stub = sinon.stub(object,method);


存根函数替换object.method。可以通过调用
object.method.restore(); (或 stub.restore(); )。如果属性不是函数,则抛出
异常,以帮助避免在
存根方法时出现拼写错误。

var stub = sinon.stub(object, "method");
Replaces object.method with a stub function. The original function can be restored by calling object.method.restore(); (or stub.restore();). An exception is thrown if the property is not already a function, to help avoid typos when stubbing methods.

这篇关于如何使用mocha.js模拟单元测试的依赖类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆