AngularJS里面注入服务测试服务模拟 [英] AngularJS inject service mock inside service tests

查看:193
本文介绍了AngularJS里面注入服务测试服务模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图测试无济于事有一段时间了服务,并希望一些帮助。这里是我的情况:

I have been trying to test a service to no avail for some time now and was hoping for some help. Here is my situation:

我有一个服务看起来有点像这样

I have a service looking a little like this

myModule.factory('myService', ['$rootScope', '$routeParams', '$location', function($rootScope, $routeParams, $location) {

  var mySvc = {
    params: {}
  }

  // Listen to route changes.
  $rootScope.$on('$routeUpdate', mySvc.updateHandler);

  // Update @params when route changes
  mySvc.updateHandler = function(){ ... };

  ...
  ...

  return mySvc;

}]);

和我想嘲笑注入为myService'服务之前被注入到我的测试,所以我可以测试在初始化code <服务/ STRONG>在

And I want to mock the services injected into 'myService' before the service gets injected into my tests so I can test the initialization code below

  var mySvc = {
    params: {}
  }

  // Listen to route changes.
  $rootScope.$on('$routeUpdate', mySvc.updateHandler);

我用的茉莉测试和模拟。这是我想出现在

I am using Jasmine for tests and mocks. This is what I came up with for now

describe('myService', function(){
  var rootScope, target;
  beforeEach(function(){
    rootScope = jasmine.createSpyObj('rootScope', ['$on']);

    module('myModule');
    angular.module('Mocks', []).service('$rootScope', rootScope );
    inject(function(myService){
      target = myService;
    });        
  });

  it('should be defined', function(){
    expect(target).toBeDefined();
  });

  it('should have an empty list of params', function(){
    expect(target.params).toEqual({});
  });

  it('should have called rootScope.$on', function(){
    expect(rootScope.$on).toHaveBeenCalled();
  });
});

这不,虽然工作。我rootscope假装不替换原始和依赖注入的DOC困惑我比什么都重要。

This doesn't work though. My rootscope mock is not replacing the original and the Dependency Injection doc is confusing me more than anything.

请帮忙

推荐答案

我想窥探的实际$ rootScope而不是试图注入自己的自定义对象。

I would spy on the actual $rootScope instead of trying to inject your own custom object.

var target, rootScope;
beforeEach(inject(function($rootScope) {
  rootScope = $rootScope;

  // Mock everything here
  spyOn(rootScope, "$on")
}));

beforeEach(inject(function(myService) {
  target = myService;
}));

it('should have called rootScope.$on', function(){
  expect(rootScope.$on).toHaveBeenCalled();
});

我在CoffeScript测试这一点,但code以上的应该仍然工作。

I've tested this in CoffeScript, but the code above should still work.

这篇关于AngularJS里面注入服务测试服务模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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