单元测试AngularJS有依赖性工厂 [英] Unit testing AngularJS factories that have dependencies

查看:161
本文介绍了单元测试AngularJS有依赖性工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单元测试的角度工厂(与噶+茉莉花),我怎么注入被测存根依赖进工厂?

When unit testing an Angular factory (with Karma + Jasmine), how do I inject a stub dependency into the factory under test?

下面是我厂:

mod = angular.module('myFactoryMod', []);

mod.factory('myFactory', [
  '$log', 'oneOfMyOtherServices', function($log, svc) {
    return makeSomethingThatDoesSomethingWithTheseDependencies($log, svc);
  }
]);

oneOfMyOtherServices 实例我厂的时候是必要的。

oneOfMyOtherServices is needed when instantiating my factory.

下面是我的测试:

it('can get an instance of my factory', function() {
  var oneOfMyOtherServicesStub;

  angular.mock.module('myFactoryMod');

  oneOfMyOtherServicesStub = {
    someVariable: 1
  };

  //****How do I get my stub in my target? ****

  angular.mock.inject(['myFactory', function(target) {

      expect(target).toBeDefined();

    }
  ]);
})

N.B。我知道, $控制器允许这样的控制器,但我没有看到工厂等效。

N.B. I know that $controller allows this for controllers, but I don't see an equivalent for factories.

推荐答案

有两种方式来完成这样的事,我知道的:

There are two ways to accomplish something like this that I know of:


  1. 使用 $提供和一个匿名模块注入模拟。

  2. 注入您想嘲笑和使用茉莉花的间谍能力提供模拟值的服务。

  1. Use $provide and an anonymous module to inject the mock.
  2. Inject the service you would like to mock and use jasmine's spying ability to provide mock values.

如果你确切地知道哪些方法测试下你的code将调用注入的服务,您可以轻松地模拟出来的第二个选项只适用。你似乎对服务(而不是方法)来访问数据属性追求的第一选择可能是最好的。

The second option only works if you know exactly which methods your code under test will be calling on the injected service and you can easily mock them out. As you seem to be accessing a data property on the service (rather than a method) pursuing the first option might be best.

使用 $提供将大致是这样的:

describe('myFactory', function () {
  // Load your module.
  beforeEach(module('myFactoryMod'));

  // Setup the mock service in an anonymous module.
  beforeEach(module(function ($provide) {
    $provide.value('oneOfMyOtherServicesStub', {
        someVariable: 1
    });
  }));

  it('can get an instance of my factory', inject(function(myFactory) {
    expect(myFactory).toBeDefined();
  }));
});

这篇关于单元测试AngularJS有依赖性工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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