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

问题描述

在对 Angular 工厂(使用 Karma + Jasmine)进行单元测试时,如何将存根依赖项注入被测工厂?

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();

    }
  ]);
})

注意我知道 $controller 允许控制器这样做,但我没有看到工厂的等效项.

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. 使用 $provide 和匿名模块来注入模拟.
  2. 注入您要模拟的服务,并使用 jasmine 的间谍功能提供模拟值.
  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.

第二个选项只有在您确切知道您的测试代码将在注入的服务上调用哪些方法并且您可以轻松地模拟它们时才有效.由于您似乎正在访问服务上的数据属性(而不是方法),因此选择第一个选项可能是最好的.

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.

使用 $provide 大致如下所示:

Using $provide would roughly look like this:

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 工厂进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:51