如何在RequireJS中模拟单元测试的依赖项? [英] How can I mock dependencies for unit testing in RequireJS?

查看:209
本文介绍了如何在RequireJS中模拟单元测试的依赖项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我想要测试的AMD模块,但我想模拟它的依赖项,而不是加载实际的依赖项。我正在使用requirejs,我的模块的代码如下所示:

I have an AMD module I want to test, but I want to mock out its dependencies instead of loading the actual dependencies. I am using requirejs, and the code for my module looks something like this:

define(['hurp', 'durp'], function(Hurp, Durp) {
  return {
    foo: function () {
      console.log(Hurp.beans)
    },
    bar: function () {
      console.log(Durp.beans)
    }
  }
}

如何模拟 hurp durp 这样我才能有效地进行单元测试?

How can I mock out hurp and durp so I can effectively unit test?

推荐答案

所以在阅读这篇文章我想出了一个解决方案,它使用requirejs配置函数为你的测试创建一个新的上下文,你可以简单地模拟你的依赖项:

So after reading this post I came up with a solution that use the requirejs config function to create a new context for your test where you can simply mock your dependencies:

var cnt = 0;
function createContext(stubs) {
  cnt++;
  var map = {};

  var i18n = stubs.i18n;
  stubs.i18n = {
    load: sinon.spy(function(name, req, onLoad) {
      onLoad(i18n);
    })
  };

  _.each(stubs, function(value, key) {
    var stubName = 'stub' + key + cnt;

    map[key] = stubName;

    define(stubName, function() {
      return value;
    });
  });

  return require.config({
    context: "context_" + cnt,
    map: {
      "*": map
    },
    baseUrl: 'js/cfe/app/'
  });
}

因此它会创建一个新的上下文,其中的定义Hurp Durp 将由您传递给函数的对象设置。这个名字的Math.random可能有点脏,但它有效。因为如果你有一堆测试,你需要为每个套件创建新的上下文,以防止重用你的模拟,或者当你想要真正的requirejs模块时加载模拟。

So it creates a new context where the definitions for Hurp and Durp will be set by the objects you passed into the function. The Math.random for the name is maybe a bit dirty but it works. Cause if you'll have a bunch of test you need to create new context for every suite to prevent reusing your mocks, or to load mocks when you want the real requirejs module.

在你的情况下,它看起来像这样:

In your case it would look like this:

(function () {

  var stubs =  {
    hurp: 'hurp',
    durp: 'durp'
  };
  var context = createContext(stubs);

  context(['yourModuleName'], function (yourModule) {

    //your normal jasmine test starts here

    describe("yourModuleName", function () {
      it('should log', function(){
         spyOn(console, 'log');
         yourModule.foo();

         expect(console.log).toHasBeenCalledWith('hurp');
      })
    });
  });
})();

所以我在生产中使用这种方法已经有一段时间了,而且非常强大。

So I'm using this approach in production for a while and its really robust.

这篇关于如何在RequireJS中模拟单元测试的依赖项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆