如何测试使用当前$location获取当前 lo 的角度服务,使用 Jasmine 获取当前主机



我用茉莉花创建了一个测试,检查是否为我提供了API端点的服务是否正常工作。我正在获取默认值,因为单元测试中的应用程序未在本地主机中运行。那么我如何在 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;
            }
        }
    };
})();
监视

$location服务上的host方法,并告诉间谍返回所需的值。同样的模式可以应用于任何服务,无论它们是否是本机 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);
});

最新更新