5

我有这些文件:

文件1.js

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

文件2.js

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

现在在为 File2 编写单元测试时,是否可以进行mod1模拟,以便我不调用mod1.someFunction()

4

2 回答 2

5

我通常使用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');
};

测试/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模块构建模拟非常方便。

于 2016-02-01T19:57:04.380 回答
2

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

https://github.com/jhnns/rewire

https://github.com/mfncooper/mockery

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

于 2016-02-01T19:48:29.290 回答