Mocha / Sinon单元测试JS类和实例问题

时间:2018-02-23 08:41:14

标签: javascript unit-testing express sinon chai

我试图对一些依赖于某些类的快速中间件进行单元测试。

Middleware.js

const MyClass = require('../../lib/MyClass');

const myClassInstance = new MyClass();

    function someMiddleware(req, res) {
        myClassInstance.get().then(function(resp) {
          res.render('somefile.html');
        });
    };

Test.js

const MyClass = require('../../lib/MyClass');
const sinon = require('sinon');
const chai = require('chai');
const expect = chai.expect;

// File we are testing
const someMiddleware = require('path/to/middleware');

MyClassMock = sinon.spy(function() {
    return sinon.createStubInstance(MyClassMock);
});
describe('My Middleware', function() {

    let renderSpy, classStub;
    let res = {
        render: function() {}
    }

    beforeEach(function() {
        renderSpy = sinon.stub(res, 'render');
    })

    afterEach(function() {
        renderSpy.restore();
    })

    it('should call render function', function() {

        someMiddleware.someMiddleware(req, res);
        expect(renderSpy.calledOnce);

    });
});

我尝试了很多东西但是我似乎很难模拟这个类并模拟创建的实例!当它运行时,它将尝试运行其中包含它的相关依赖项的实际类。

干杯人!

1 个答案:

答案 0 :(得分:0)

您的意图:替换/存储中间件的依赖关系。

您的问题:无法从模块的外部进行此操作。你不知何故需要“拦截”将使用哪些代码。

有两个选项,我在其他地方(123详细介绍了这两个选项,所以我会在这里做短文:< / p>

手动依赖注入

在中间件模块中,提供仅从测试中调用的__setMyClassInstance(stubbedInstance)方法。

  • Pro:非常简单,不需要框架
  • Con:打开模块的仅测试代码

链接接缝

这是关于用另一个返回您喜欢的对象的模块加载器替换代码中的require()调用。在您的测试代码中:

const myMiddleware = proxyquire('../../src/middleware', { '../../lib/MyClass': myStubbedInstance })
  • Pro:与DI相同,但模块中不需要更改代码
  • 骗局:不是明确了解正在发生的事情,需要学习新的依赖

如果您在查看这些非常简短的解释后感到困惑,我建议您查看我提供的长篇解释链接以及指向链接Seam库(如proxyquirerewire)教程的链接。< / p>