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.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...