我创建了一个包装环境信息的Env服务,我现在正在使用$location.host()来确定我所处的环境.如何在我的测试中模拟它?
我读过https://groups.google.com/forum/?fromgroups#!topic/angular/F0jFWC4G9hI,但它似乎不起作用,例如:
describe("Env (environment) service",function() { var Env; beforeEach(module('App')); beforeEach(inject( ['Env',function(e) { Env = e; }] )); describe("for staging",function() { beforeEach(inject(function($location,$rootScope) { $location.host("http://staging-site.com"); $rootScope.$apply(); })); it("returns envrionment as staging",function() { expect(Env.environment).toEqual("staging"); }); it("returns .isStaging() as true",function() { expect(Env.isStaging()).toBeTruthy(); }); }); });
我也尝试了$浏览器变体,但这也不起作用.有任何想法吗?
解决方法
最好的方法是使用间谍恕我直言:
http://tobyho.com/2011/12/15/jasmine-spy-cheatsheet/
// inject $location spyOn($location,"host").andReturn("super.domain.com"); var host = $location.host(); alert(host) // is "super.domain.com" expect($location.host).toHaveBeenCalled();