茉莉花模拟对象在测试中

时间:2015-12-22 10:51:51

标签: angularjs jasmine

模拟对象服务是否可行?是否可以模拟cfg.user.core.token的值?我这样嘲笑httpBackend:

   $httpBackend.when("GET","/check/").respond({
                data: ['success']
              });

这是我的代码:

.service("session", function ($window, $location, $http, cfg) {
        var service = {};
        service.check = function () {
            $http.get("/chceck/" + cfg.user.core.token).then(function (response) {
                if (response.data && response.data.success !== true) {
                    service.logout();
                }
            });
        };
    return service;
})

我的测试部分:

it("check ", function () {
   spyOn(session, 'check').and.callThrough();
   session.check();
   expect(session.check).toHaveBeenCalled();
   $httpBackend.flush();
  });

1 个答案:

答案 0 :(得分:0)

假设cfg是一个角度常数:

angular.module('mymodule')
  .constant('cfg', {
    user: {
      core: {
        token: 'token'
      }
    }
  });

因此,在Jasmine测试中,您可以将此常量存根:

describe('mytest', function () {
  var 
    cfgStub = {
      user: {
        core: {
          token: 'stubToken'
        }
      }
    };

  beforeEach(module('mymodule'));

  beforeEach(module(function($provide) {
    $provide.constant('cfg', cfgStub);
  }));

  ...
});

在测试中的任何地方使用cfgStub

相关问题