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

查看:29
本文介绍了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' 中的服务,以便我可以测试下面的初始化代码

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

我使用 Jasmine 进行测试和模拟.这就是我现在想到的

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 模拟并没有取代原来的,而且依赖注入文档比任何事情都让我感到困惑.

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 中对此进行了测试,但上面的代码应该仍然有效.

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

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

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