1

大家下午好,

只想问一下如何在单元测试中正确设置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 方法是否被调用并且它确实被调用了。请帮忙。

4

1 回答 1

2

您嘲笑了add服务中的方法。如果要在监视它时调用它,则需要使用andCallThrough()

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

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

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

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

根据token的价值,你可以做expect(location.path()).toBe('/registeredUserOnly')

于 2013-09-12T07:37:11.913 回答