1

我的 ng 应用程序运行良好,但我正在尝试为我的控制器编写一个 ngMock 测试;我基本上遵循 Angular 网站上的示例:https : //docs.angularjs.org/api/ngMock/service/ $httpBackend

我遇到的问题是即使在预期请求时它也会抱怨意外请求。

PhantomJS 1.9.8 (Windows 8 0.0.0) NotificationsController 应该获取通知列表失败

错误:意外请求:GET 对测试 API/AspNetController/AspNetAction 无效预期 GET api/AspNetController/AspNetAction

我没有得到的是,在错误行上,为什么在我的服务 URL 之前附加了一个“测试”字样?我认为它应该发送到 'api/AspNetController/AspNetAction' 我在这里做错了什么。我找不到任何其他人通过谷歌遇到与我相同的问题。

编辑:我注意到,如果我从控制器中删除 sendRequest 部分,并让单元测试在控制台中记录我的请求对象,我会看到以下 json。

{  
   "method":"GET",
   "url":"Not valid for testsapi/AspNetController/AspNetAction",
   "headers":{  
      "Content-Type":"application/json"
   }
}

这是控制器代码

angular.module('MainModule')
    .controller('NotificationsController', ['$scope', '$location', '$timeout', 'dataService',
        function ($scope, $location, $timeout, dataService) {
            //createRequest returns a request object
            var fetchNotificationsRequest = dataService.createRequest('GET', 'api/AspNetController/AspNetAction', null);
            //sendRequest sends the request object using $http
            var fetchNotificationsPromise = dataService.sendRequest(fetchNotificationsRequest);
            fetchNotificationsPromise.then(function (data) {
                //do something with data.
            }, function (error) {
                alert("Unable to fetch notifications.");
            });
    }]
);

测试代码

describe('NotificationsController', function () {
    beforeEach(module('MainModule'));
    beforeEach(module('DataModule')); //for data service

    var $httpBackend, $scope, $location, $timeout, dataService;

    beforeEach(inject(function ($injector) {

        $httpBackend = $injector.get('$httpBackend');

        $scope = $injector.get('$rootScope');
        $location = $injector.get('$location');
        $timeout = $injector.get('$timeout');
        dataService = $injector.get('dataService');

        var $controller = $injector.get('$controller');

        createController = function () {
            return $controller('NotificationsController', {
                '$scope': $scope,
                '$location': $location,
                '$timeout': $timeout,
                'dataService': dataService,
            });
        };
    }));

    afterEach(function () {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('should fetch notification list', function () {
        $httpBackend.expectGET('api/AspNetController/AspNetAction');        //this is where things go wrong
        var controller = createController();

        $httpBackend.flush();
    });

});

数据服务代码

    service.createRequest = function(method, service, data) {
        var req = {
            method: method, //GET or POST
            url: someInjectedConstant.baseUrl + service,
            headers: {
                'Content-Type': 'application/json'
            }
        }

        if (data != null) {
            req.data = data;
        }

        return req;
    }

    service.sendRequest = function (req) {
        return $q(function (resolve, reject) {
            $http(req).then(function successCallback(response) {
                console.info("Incoming response: " + req.url);
                console.info("Status: " + response.status);
                console.info(JSON.stringify(response));

                if (response.status >= 200 && response.status < 300) {
                    resolve(response.data);
                } else {
                    reject(response);
                }
            }, function failCallback(response) {
                console.info("Incoming response: " + req.url);
                console.info("Error Status: " + response.status);
                console.info(JSON.stringify(response));

                reject(response);
            });
        });
    }

回答:

由于 dataService 通过someInjectedConstant .baseUrl + 从控制器传入的whatever_relative_url 创建了最终的webapi url,在我正在编写的测试中,我将不得不注入someInjectedConstant

$httpBackend.expectGET(someInjectedConstant.baseUrl + relativeUrl)

而不是仅仅做一个 $httpBackend.expectGET(relativeUrl)

4

1 回答 1

0

显然Not valid for tests是在您的代码中某处添加到您的网址。它也没有添加硬编码域(见下面的注释)。检查您的所有代码以及可能将其添加到 url 的测试管道的任何其他部分。

您的代码有几点:

  • 避免在您的代码中对域名进行硬编码(我看到您已在更新的答案中解决了这个问题)
  • 也许someInjectedConstant可以更明确地命名
  • 你不需要用 包裹$http$q所以service.sendRequest可以:

    service.sendRequest = function (req) {
        $http(req).then(function (response) { // no need to name the function unless you want to call another function with all success/error code in defined elsewhere
            console.info("Incoming response: " + req.url);
            console.info("Status: " + response.status);
            console.info(JSON.stringify(response));
            return response.data; // angular treats only 2xx codes as success
        }, function(error) {
            console.info("Incoming response: " + req.url);
            console.info("Error Status: " + response.status);
            console.info(JSON.stringify(response));
        });
    }
    
于 2015-11-23T21:17:59.287 回答