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

标签 javascript node.js unit-testing mocha.js

鉴于我有两个 ES6 类。

这是A类:

import B from 'B';

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

B 类:

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

我正在使用 mocha(对于 ES6 使用 babel)、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???
    });
});

最佳答案

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

测试可能如下所示:(sinon < v3.0.0)

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

编辑:对于 sinon 版本 >= v3.0.0,使用这个:

describe("Class A", () => {

    var InstanceOfA;

    beforeEach(() => {
        InstanceOfA = new A();
    });

    it('should call B', () => {
        sinon.stub(B.prototype, 'doSomething').callsFake(() => '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.

关于javascript - 如何使用 mocha.js 模拟用于单元测试的依赖类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32695244/

相关文章:

mongodb - 在 mongodb 中加入类似查询

node.js - 从 Sabre 请求 SeatMap 信息时出现错误代码 "ERR.RAF.APPLICATION"是什么意思?

java - Mockito 不能模拟这个类

java - 如何在 vert.x java 中对处理程序进行单元测试?

python - 是否有适用于 Python 的首选 BDD 样式单元测试框架?

javascript - MAC M1 安装 "sharp"模块出现问题

javascript - 将时区偏移小时数转换为时区偏移(军事?)小时数

javascript - 基于 Javascript 变量值的多个 SVG 动画的设置时间已经过去

javascript - 无法删除 Meteor.js 中的 Mongodb 索引

javascript - 未捕获的类型错误 : Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined