AngularJS_UnitTesting:未发生预期的呼叫

时间:2016-02-16 10:48:59

标签: angularjs unit-testing

我的单一测试功能

function get(url, headers) {
        var config =
        {
            method: 'GET',
            url: url,
            headers: headers
        };
        return httpHandler(config);
    }

测试用例我正在写

it(" When method is called with url but no header passed  \n", function () { 
            var url=baseURL + "check/HttpGET";
            httpWrapperService.get(url);
            //spy here
            expect(httpWrapperService.httpHandler).toHaveBeenCalled();
 });

spyOn(httpWrapperService, 'httpHandler').and.callFake(function(){
               //do nothing
 });

我试图在初始化时将spyOn放在测试之前,Itried将它放在每个地方,但每次我运行测试时都会说

" Expected spy httpHandler to have been called." 

我无法弄清楚它为什么不起作用。

修改

添加更多代码行

beforeEach(function () {
        module("safe-repository");

        // Inject needed services
        inject(function ($scope, $httpBackend, _statusService_ , _httpWrapperService_, _settingsService_) {
            statusService=_statusService_;
            httpWrapperService=_httpWrapperService_;
            httpBackend=$httpBackend;
            settingsService=_settingsService_;
            scope=$scope;
            // Get baseUrl
            baseURL = settingsService.getServicesURL();
            // Default answer
            httpBackend.whenGET("languages/en.json").respond("OK");
            spyOn(httpWrapperService, 'httpHandler').and.callFake(function(){
               //do nothing
            });
          });
    });

1 个答案:

答案 0 :(得分:0)

如果get函数在wrapperService上,我认为问题在于你没有调用$ scope的apply函数,以及#34; digest"角度JS标准循环。

尝试这样的事情:

it(" When method is called with url but no header passed  \n", function () { 
        //Arrange
        var url=baseURL + "check/HttpGET";
        httpWrapperService.get(url);
        // Act
         $scope.apply();
        //Assert
        expect(httpWrapperService.httpHandler).toHaveBeenCalled();
 });