无法在单元测试中设置localStorage / cookie

时间:2013-09-12 07:21:58

标签: unit-testing angularjs jasmine

大家下午好,

只想询问如何在单元测试中正确设置localStorage / cookie的值。我在下面的代码中设置了一个cookie,然后尝试获取该cookie的值,但它始终显示为null。

这段代码是我正在尝试测试的代码:

scope.$on("$locationChangeSuccess", function(event, next, current) 
    {
        if(location.path() === '/home') {
            if(!Utils.isBlank(session.get('token'))) {
                    var usertype = session.get('usertype');
                    // console.log('landed home');
                    if(usertype === 'player') location.path('/user/dashboard');
                    if(usertype === 'broadcaster') location.path('/broadcaster/dashboard');
                    if(usertype === 'quizmaster') location.path('/quizmaster/dashboard');         
            }
        }   
    });

我的controllerSpec.js

describe('MainCtrl', function() {

var scope, api, security, clearAll, location, redirect, session, utility;
beforeEach(inject(function($rootScope, $controller ,$location, Api, Security, Utils, localStorageService){
    scope = $rootScope.$new();
    location = $location;
    session = localStorageService
    utility = Utils;

    $controller("MainCtrl", {
        $scope : scope,
        localStorageService : session,
        Api : Api,
        $location : location,
        Utility : utility
    });
}));

it('should expect player to be redirected to /user/dashboard', function() {
  //set the location to home
  var home = spyOn(location, 'path');
  var addSession = spyOn(session, 'add');
  var token = 'testToken';

  location.path('/home');

  scope.$on('$locationChangeSuccess', {})
  expect(home).toHaveBeenCalledWith('/home');

  //mock a session
  session.add('token',token);
  expect(addSession).toHaveBeenCalled();
  expect(session.get('token')).toEqual('testToken');
});

错误:

Chrome 24.0 (Linux) controllers MainCtrl MainCtrl should expect player to be redirected to /user/dashboard FAILED
Expected null to equal 'testToken'.

即使我已经设置了令牌“session.add('token',token)”,它仍然显示令牌为空。我添加了一个spyOn来检查是否调用了session.add方法并且确实调用了它。 请帮忙。

1 个答案:

答案 0 :(得分:2)

您在服务中模拟了方法add。如果你想在侦察它时调用它,你需要使用andCallThrough()

var addSession = spyOn(session, 'add').andCallThrough();

如果您是Jasmine的新手,这可能并不明显。有一个问题(找不到,抱歉),人们抱怨这应该是spyOn的默认功能。恕我直言,这是好的方式,因为你应该只做单元测试,不要指望你的控制器做一个完整的集成测试(即删除session.get期望,你没有测试会话工作,有进入图书馆测试)。

更新回答您的评论,根据存储在本地存储中的令牌测试网址,只需执行以下操作:

spyOn(session, 'get').andReturn(token); //Remember, you are not testing the service, you assume it works.

根据令牌的价值,您可以执行expect(location.path()).toBe('/registeredUserOnly')