2016-08-23 59 views
0

这是我处理导航的简单服务。 如果用户按照当前状态点击“下一个”,他将被重定向到下一页。如何在angularjs服务中测试一个函数

'use strict'; 

angular 
.module('myAngularmodule') 
.service('ButtonBarService', 
function ($state, StatesConstants) { 

    return { 
     next: next 
    }; 

    function next() { 
     switch ($state.current.name) { 
      case StatesConstants.LICENSE : 
       $state.go(StatesConstants.APPLICATIONGROUP); 
       break; 
      case StatesConstants.APPLICATIONGROUP : 
       $state.go(StatesConstants.ANALYSIS); 
       break; 
      default: 
       break; 
     } 
    } 


}); 

这是我的规格文件,当我试图测试失败

'use strict'; 

describe('ButtonBarService', function() { 

beforeEach(module('myAngularmodule')); 
var ButtonBarService; 

beforeEach(inject(function (_ButtonBarService_) { 
    ButtonBarService = _ButtonBarService_; 

    spyOn(ButtonBarService, 'next'); 

})); 

describe('next()', function() { 

    it('should retrieve the current user', function() { 
     expect(ButtonBarService.next).toHaveBeenCalled(); 
    }); 

}); 

}); 

失败说“下一个预期的间谍已被称为”。 这个服务没有后端的东西,我只是推广它来处理buttonbar的东西。 我对前端颇为陌生。我看到有$ http的答案,但无法理解。

+0

您需要检查内部函数在做什么。您需要在每个函数之前添加'ButtonBarService.next()',然后检查期望 –

+0

您能否详细回答这个问题。我已经在监视它。我需要做其他事吗? – ankitd

+0

你正在测试错误的东西,我的意思是说,你必须测试'$ state.go(StatesConstants.APPLICATIONGROUP);'在某些条件下...你所做的期望应该是其他服务或控制器的一部分 –

回答

0

尝试(书面ES6语法):

spyOn(ButtonBarService, 'next').and.callFake(() => true); 

那么你的预期应该工作,我想。

+0

感谢@rrd,但它没有奏效。 – ankitd