我用jasmine创建了一个测试,检查是给我的API端点工作的服务。我得到默认值,因为单元测试中的应用程序没有在localhost中运行。那么如何在mu单元测试中模拟该功能呢。
这是我的单元测试:
describe("EndpointService->", getApiEndPoint);
function getApiEndPoint() {
beforeEach(function () {
module('app');
});
it("GetApiEndpointUriBaseOnCurrentHost", inject(function (endpointService) {
//Arrange
var expectedUriInLocalhostEnviroment = 'not recognized client host';
//Act
var uriEndPoint = endpointService.getApiEndpoint();
//Assert
expect(uriEndPoint).toMatch(expectedUriInLocalhostEnviroment);
}));
};
这是我的服务。它使用$location
来获取本地主机:
(function () {
'use strict'
var app = angular.module('app');
app.factory('endpointService', endpointService);
function endpointService($location) {
return {
getApiEndpoint: function () {
var endpoint = '';
var host = $location.host();
switch ($location.host()) {
case 'localhost': endpoint = 'http://localhost:59987/'; break;
case 'projectDev': endpoint = 'http://project.com'; break;
default: endpoint = 'not recognized client host';
}
return endpoint;
}
}
};
})();
答案 0 :(得分:0)
监视host
服务上的$location
方法并告诉间谍返回您想要的值。这种模式可以适用于任何服务,无论它们是否是本机Angular服务。
var $location;
beforeEach(module('app'));
beforeEach(inject(function (_$location_) {
$location = _$location_;
spyOn($location, 'host');
}));
it('should get endpoint for localhost', function () {
// Arrange
$location.host.and.returnValue('localhost');
var expected = 'http://localhost:59987/';
// Act
var uriEndPoint = endpointService.getApiEndpoint();
// Assert
expect(uriEndPoint).toEqual(expected);
});