我正在为服务编写单元测试并且遇到 $ rootScope.hideLogout(); 方法的问题(请参阅下面的服务代码),因为它是在控制器中定义的而我不是从我的测试中访问(至少我是这么认为)这个控制器,我收到错误:
对象不支持属性或方法'hideLogout'
这是我的测试:
it('should logout when player is in the system', function () {
var user = {
name: 'player name',
password: 'password'
};
var userData = {
access_token: 'token',
token_type: 'bearer',
expires_in: 1209599,
userName: 'Player@maildomain.com',
issued: "Fri, 12 Feb 2016 12:02:37 GMT",
expires: 'Thu, 25 Feb 2016 13:22:45 GMT',
userId: 2,
accountType: 'Player',
certifiedForAccess: true
}
localStorage.setItem('userAuth', JSON.stringify(user));
localStorage.setItem('tokenKey', JSON.stringify(userData));
localStorage.setItem('userId', userData.userId);
authSvc.logOut(true, function() {}); // not sure about callback, so decided to put empty function for now
var resultToken = localStorage.getItem('tokenKey');
expect(localStorage.getItem('tokenKey')).toBeNull();
expect(localStorage.getItem('userAuth')).toBeNull();
expect(localStorage.getItem('userId')).toBeNull();
});
我的 beforeEach()功能:
beforeEach(function() {
module('app');
inject(function (_AuthService_, $q, $rootScope, $httpBackend, $state, _config_, _messages_) {
scope = $rootScope;
authSvc = _AuthService_;
httpBackend = $httpBackend;
config = _config_;
});
});
要测试的服务方法:
function logOut(logoutAnyway, cancelLogoutCallback) {
if (logoutAnyway || !svc.isAdministrator()) {
$rootScope.hideLogout(true);
localStorage.removeItem(userIdKey);
localStorage.removeItem(userAuthKey);
localStorage.removeItem(tokenKey);
$state.go('login');
svc.fakeUserId = null;
} else {
$rootScope.showLogout(cancelLogoutCallback);
}
}
你能指点一下如何处理它吗?
答案 0 :(得分:0)
尝试在测试中使用scope = $rootScope.new()
。
<强>更新强>
您还需要使用Jasmine的spyOn
方法。
spyOn(scope , 'hideLogout');
spyOn(scope , 'showLogout');
更新2
在scope = $rootScope.new()
尝试模拟$rootScope
scope.hideLogout = function () {};
scope.showLogout = function () {};
然后添加代码的spyOn
部分