Jasmine和AngularJS - 单元测试模拟依赖

时间:2016-04-01 14:41:23

标签: angularjs jasmine

我有AuthService依赖userService来自不同的模块

我正在尝试编写一个单元测试来检查我已经模拟过的userService的属性,并在我的测试规范中使用$ provide服务。

beforeEach(function() {
    module('app.services');
    //Need to provide userService since it lives in a different module
    module(function ($provide) {
        $provide.value('userService', function(){
            return {
                userLoggedIn: false
            }
        });
    });
});

//Question - will injecting _userService_ pick up the mocked instance from above?
beforeEach(inject(function(_AuthService_, _userService_) {
    authService = _AuthService_;
    userService = _userService_;
}));

describe('some text', function() {
    it('should make a get request to check the users token', function() {
        $httpBackend.expectGET('/auth/checktoken').respond({});
        authService.hasAccessToken();
        $httpBackend.flush();
    });
    it('should set userService.userLoggedIn to be true', function() {
        expect(userService.userLoggedIn).toBeTruthy();
    });
});

我对userService的期望失败,因为它返回未定义。我需要做些什么才能测试我的模拟userService

由于

更新

好的,根据评论,我可以通过组织我的测试来完成它

  describe('hasAccessToken', function() {
    beforeEach(function(){
      authService.hasAccessToken();
    });
    it('should make a get request to catalogues', function() {
      $httpBackend.expectGET('/auth/checktoken').respond({});
      $httpBackend.flush();
    });
    it('should set userService.userLoggedIn to be true', function() {
      $httpBackend.expectGET('/auth/checktoken').respond({});
      $httpBackend.flush();
      expect(userService.userLoggedIn).toBeTruthy();
    });
  });

正如您所看到的那样,我试图分别为expectGET和userService编写测试,这是正确的吗?看起来很啰嗦??

1 个答案:

答案 0 :(得分:0)

您正在为提供者使用angular value合成糖,但是您提供了一个构造函数,该构造函数应与service语法一起使用。

尝试使用带有service语法的服务构造函数:

beforeEach(module(function ($provide) {
    $provide.service('userService', function(){
        return {
            userLoggedIn: false
        }
    });
});

或者只使用value语法的服务实例:

beforeEach(module(function ($provide) {
    $provide.value('userService', {
            userLoggedIn: false
        }
    });
});

请参阅angular docs:$provide