考虑到我有两门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类就不会执行真正的代码,但我可以提供测试功能.

这就是目前的摩卡测试:

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

EDIT: for sinon versions >= v3.0.0, use this:

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.

Node.js相关问答推荐

nest js控制器方法调用两次

Express 4.18正文解析

模块';"; node :流程&没有导出的成员';dlopen';

获取页面大小为10的所有文章,每篇文章填充一些所需的用户信息

使用参考中断Mongoose模型-Node.js

仅在一次查询中 MongoDB 上最近的一对位置

dayjs的isSameOrAfter方法未按预期工作

npm 在 Windows 终端中不工作

Axios 响应循环通过函数只返回第一个映射对象的结果

处理 UTC 日期和future

如何在没有 Typescript 的情况下以交互方式使用 Create-React-App?

为什么 $or 在带有正则表达式的mongoose 中不能正常工作

使用 Socket.io 将客户端连接到服务器

将 myproject/.npmrc 与注册表一起使用

无法获取 CSS 文件

MongoDB Node findone如何处理没有结果?

chart.js 无法创建图表:无法从给定项目获取上下文

Fluxible 中的脱水和再水合代表什么?

NodeJS 中的 HTTPS 请求

如何让 Mocha 加载定义全局挂钩或实用程序的 helper.js 文件?