如何在 mocha 测试中模拟全局变量(定义、模块、窗口)?

Ste*_*Dev 8 javascript unit-testing mocha.js node.js

在追求100%的代码覆盖率的,我试图用摩卡来测试我的javascript模块下正确加载AMDCommonJS/Nodebrowser条件。我使用的模式如下:

我的module.js

(function(global){

  function MyClass(){}

  // AMD
  if(typeof define === 'function' && define.amd){
    define(function(){
      return MyClass;
    });

  // CommonJS/Node
  } else if (typeof module !== 'undefined' && module.exports){
    module.exports = MyClass;

  // Browser
  } else {
    global.MyClass = MyClass;
  }

})(this);
Run Code Online (Sandbox Code Playgroud)

由于我使用 node 运行我的测试,define因此从未定义,并且module始终已定义;所以“CommonJS/Node”条件是唯一经过测试的条件。

到目前为止我尝试过的是这样的:

我的module.test.js

var MyClass = require('./my-module');

describe('MyClass', function(){
  // suite of tests for the class itself
  // uses 'var instance = new MyClass();' in each test
  // all of these tests pass
});

describe('Exports', function(){
  // suite of tests for the export portion
  beforeEach(function(){
    MyClass = null; // will reload module for each test
    define = null; // set 'define' to null
    module = null; // set 'module' to null
  });

  // tests for AMD
  describe('AMD', function(){
    it('should have loaded as AMD module', function(){
      var define = function(){};
      define.amd = true;

      MyClass = require('./my-module'); // might be cached?
      // hoping this reloads with 'define' in its parent scope
      // but it does not. AMD condition is never reached.

      expect(spy).to.have.been.called(); // chai spy, code omitted
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

我正在使用 spies 检查是否define已被调用,但该模块没有显示任何重新加载define可用的迹象。我怎样才能做到这一点?

是否有一种安全的无效方法,module以便我也可以测试浏览器条件?

Ste*_*Dev 2

我能够创建一个自定义解决方案(从http://howtonode.org/testing-private-state-and-mocking-deps借用此代码的大部分)

模块加载器.js

require该模块基本上创建了一个新的上下文,您的自定义属性在与和console等相同的全局空间中可用。

var vm = require('vm');
var fs = require('fs');
var path = require('path');
var extend = require('extend'); // install from npm

/**
 * Helper for unit testing:
 * - load module with mocked dependencies
 * - allow accessing private state of the module
 *
 * @param {string} filePath Absolute path to module (file to load)
 * @param {Object=} mocks Hash of mocked dependencies
 */
exports.loadModule = function(filePath, mocks) {
  mocks = mocks || {};

  // this is necessary to allow relative path modules within loaded file
  // i.e. requiring ./some inside file /a/b.js needs to be resolved to /a/some
  var resolveModule = function(module) {
    if (module.charAt(0) !== '.') return module;
    return path.resolve(path.dirname(filePath), module);
  };

  var exports = {};
  var context = {
    require: function(name) {
      return mocks[name] || require(resolveModule(name));
    },
    console: console,
    exports: exports,
    module: {
      exports: exports
    }
  };

  var extendMe = {};
  extend(true, extendMe, context, mocks);

  // runs your module in a VM with a new context containing your mocks
  // http://nodejs.org/api/vm.html#vm_vm_runinnewcontext_code_sandbox_filename
  vm.runInNewContext(fs.readFileSync(filePath), extendMe);

  return extendMe;
};
Run Code Online (Sandbox Code Playgroud)

我的模块.test.js

var loadModule = require('./module-loader').loadModule;

// ...

it('should load module with mocked global vars', function(){
  function mockMethod(str){
    console.log("mock: "+str);
  }

  var MyMockModule = loadModule('./my-module.js', {mock:mockMethod});
  // 'MyClass' is available as MyMockModule.module.exports
});
Run Code Online (Sandbox Code Playgroud)

我的模块.js

(function(global){

  function MyClass(){}

  if(typeof mock !== 'undefined'){ 
    mock("testing"); // will log "mock: testing"
  }

  module.exports = MyClass;

})(this);
Run Code Online (Sandbox Code Playgroud)