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



大家下午好,

只是想问如何在单元测试中正确设置 localStorage/cookie 的值。我在下面有这段代码,我在其中设置了一个 cookie,然后尝试获取该 cookie 的值,但它总是为空。

这段代码是我尝试测试的代码片段:

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');         
            }
        }   
    });

我的控制器规格.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 方法,它确实被调用了。请帮忙。

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

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

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

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

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

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

最新更新