ngMock在预期请求时抱怨意外请求

ngMock complains unexpected request when request is expected

本文关键字:请求 意外 ngMock      更新时间:2023-09-26

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

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

PhantomJS 1.9.8(Windows 8 0.0.0)通知控制器应获取通知列表FAILED

错误:意外请求:GET对testsapi/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,在我正在编写的测试中,我将不得不注入someInjected Constant

$httpBackend.expectGET(someInjectedConstant.baseUrl + relativeUrl)

而不是只做$httpBackend.expectGET(relativeUrl)

很明显,Not valid for tests已经在代码中的某个位置准备好了url。它也没有添加硬编码域(请参阅下面的注释)。检查您的所有代码以及测试管道中可能将其添加到url的任何其他部分。

你的代码上有几点:

  • 避免在代码中对域名进行硬编码(我看到你在更新的答案中已经解决了这个问题)
  • 也许someInjectedConstant可以更明确地命名
  • 你不需要用$q包裹$http,所以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));
        });
    }