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