【问题标题】:Mocking a nested module in Node.js?在 Node.js 中模拟嵌套模块?
【发布时间】:2016-05-10 09:32:06
【问题描述】:

我有这些文件:

文件1.js

var mod1 = require('mod1');
mod1.someFunction()
...

文件2.js

var File1 = require('./File1');

现在在为 File2 编写单元测试时,是否可以模拟 mod1,这样我就不会调用 mod1.someFunction()

【问题讨论】:

  • 是的,这是可能的。你应该阅读一些关于依赖注入的内容。看看 sinon.js。
  • 看看这个关于模拟的教程:youtube.com/watch?v=fgqh-OZjpYY 它展示了一种你可以使用的技术。是的,一定要看看 sinon。
  • sinon 将如何解决这个问题?
  • Sinon 帮助为正在创建的函数创建存根,以便验证它们是否被正确调用、返回正确的值等。

标签: javascript node.js unit-testing require proxyquire


【解决方案1】:

我通常使用mockery 模块,如下所示:

lib/file1.js

var mod1 = require('./mod1');
mod1.someFunction();

lib/file2.js

var file1 = require('./file1');

lib/mod1.js

module.exports.someFunction = function() {
  console.log('hello from mod1');
};

test/file1.js

/* globals describe, before, beforeEach, after, afterEach, it */

'use strict';

//var chai = require('chai');
//var assert = chai.assert;
//var expect = chai.expect;
//var should = chai.should();

var mockery = require('mockery');

describe('config-dir-all', function () {

  before('before', function () {
    // Mocking the mod1 module
    var mod1Mock = {
      someFunction: function() {
        console.log('hello from mocked function');
      }
    };

    // replace the module with mock for any `require`
    mockery.registerMock('mod1', mod1Mock);

    // set additional parameters
    mockery.enable({
      useCleanCache:      true,
      //warnOnReplace:      false,
      warnOnUnregistered: false
    });
  });

  beforeEach('before', function () {

  });

  afterEach('after', function () {

  });

  after('after', function () {
    // Cleanup mockery
    after(function() {
      mockery.disable();
      mockery.deregisterMock('mod1');
    });
  });

  it('should throw if directory does not exists', function () {

    // Now File2 will use mock object instead of real mod1 module
    var file2 = require('../lib/file2');

  });

});

如前所述,sinon 模块非常方便构建模拟。

【讨论】:

  • 谢谢,成功了!我之前实际上是在尝试 Mockery,但是在引号中加上了 mock 的名称,并且没有意识到。
  • 嗯.. 对我不起作用。不知道为什么。可能是因为嵌套的 require 使用的是相对路径?
【解决方案2】:

当然。有 2 个非常流行的 node.js 库专门用于模拟需求。

https://github.com/jhnns/rewire

https://github.com/mfncooper/mockery

它们都有不同的 API,并且 rewire 有一些奇怪的警告

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 2014-01-09
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    相关资源
    最近更新 更多