微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

没有在SO或网络上找到解决方案,希望有人能帮助我.

鉴于我有两个ES6课程.

这是A类:

import B from 'B';

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

和B类:

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

我使用mocha进行单元测试(用于ES6的babel),chai和sinon,它们的效果非常好.但是,当测试A类时,如何为B类提供一个模拟类?

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

这就是摩卡考试现在的样子:

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,以防止执行实际的功能.

例如,给定类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",() => {
        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”);
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.

原文地址:https://www.jb51.cc/js/151897.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐