我正在测试这个特殊功能:
function apiInjector($location, $cookies) {
var apiVersion = 1, baseUrl;
console.log('Host: '+$location.host());
if($location.host() == 'localhost') {
baseUrl = $cookies.get('API_HOST') || 'http://localhost:5000';
} else {
baseUrl = 'productionURL';
}
if(!baseUrl)
throw('Invalid host defined');
function isApiRequest(url) {
return url.substr(url.length - 5) !== '.html';
}
return {
request: function(config) {
if(isApiRequest(config.url)) {
config.url = baseUrl + '/' + apiVersion + '/' + config.url;
}
return config;
}
};
}
正如您所看到的,它使用$ location.host来确定主机是什么。我已经创建了一个模拟器,因此我可以在if-else语句中控制流程:
var apiInjector, $location;
var mockedLocation = {
host: function() {
return 'localhost';
}
};
beforeEach(module('flowlens'), function($provide) {
$provide.value('$location', mockedLocation);
});
beforeEach(inject(function(_apiInjector_, _$location_) {
apiInjector = _apiInjector_;
$location = _$location_;
}));
describe('apiInjector',function(){
it('should be defined', function() {
expect(apiInjector).toBeDefined();
});
it('should expose a request function', function() {
expect(apiInjector.request).toBeDefined();
});
});
但是当我调用函数(apiInjector.request)时,我总是在实际代码中插入console.log($ location.host())时看到 server (见上文)。我在这里做错了什么?
修改
这是打印apiInjector.request结果时打印的内容。
Object{url: 'productionURL/1/dashboard'}
但基于上面的代码并假设host()函数返回 localhost (它没有返回服务器),它应该打印出结果$ cookies.get或http://localhost:5000
答案 0 :(得分:1)
您需要在传递给beforeEach块的函数中加载模块,然后使用$provide
作为回调函数传递函数:
beforeEach(function() {
module('flowlens', function($provide) {
$provide.value('$location', mockedLocation);
});
});
或者你可以这样写:
beforeEach(module('flowlens'));
beforeEach(module(function($provide) {
$provide.value('$location', mockedLocation);
}));
或者,sinon为间谍,存根,模拟等提供了一些不错的选择。我已经用它来模仿$location
,如:
var location,
locationStub;
beforeEach(inject(function($location) {
location = $location;
locationStub = sinon.stub(location, 'url');
locationStub.returns('some/fake/url');
}