我知道当你使用spyOn
时,你可以有不同的形式,如.and.callFake
或.andCallThrough
。我真的不确定我正在尝试测试的这段代码需要哪一个......
var lastPage = $cookies.get("ptLastPage");
if (typeof lastPage !== "undefined") {
$location.path(lastPage);
} else {
$location.path('/home'); //TRYING TO TEST THIS ELSE STATEMENT
}
}
这是我的一些测试代码:
describe('Spies on cookie.get', function() {
beforeEach(inject(function() {
spyOn(cookies, 'get').and.callFake(function() {
return undefined;
});
}));
it("should work plz", function() {
cookies.get();
expect(location.path()).toBe('/home');
expect(cookies.get).toHaveBeenCalled();
expect(cookies.get).toHaveBeenCalledWith();
});
});
我尝试了很多不同的东西,但我正在尝试测试else
语句。因此,我需要制作cookies.get == undefined
.每次我尝试这样做时,我都会收到此错误:
Expected '' to be '/home'.
当cookies.get()
等于 undefined
时,location.path()
的值永远不会改变。我认为我错误地使用了间谍?
跟进我的模拟值:
beforeEach(inject(
function(_$location_, _$route_, _$rootScope_, _$cookies_) {
location = _$location_;
route = _$route_;
rootScope = _$rootScope_;
cookies = _$cookies_;
}));
职能跟进:
angular.module('buildingServicesApp', [
//data
.config(function($routeProvider) {
//stuff
.run(function($rootScope, $location, $http, $cookies)
这些函数没有名称,因此如何调用cookies.get
?
现在,您正在测试 location.path()
函数是否按设计工作。我想说你应该把测试留给AngularJS团队:)。相反,请验证是否正确调用了该函数:
describe('Spies on cookie.get', function() {
beforeEach((function() { // removed inject here, since you're not injecting anything
spyOn(cookies, 'get').and.returnValue(undefined); // As @Thomas noted in the comments
spyOn(location, 'path');
}));
it("should work plz", function() {
// cookies.get(); replace with call to the function/code which calls cookies.get()
expect(location.path).toHaveBeenCalledWith('/home');
});
});
请注意,您不应该测试您的测试模拟cookies.get
,您应该测试任何调用问题中第一段代码的函数都在做正确的事情。