我知道当您使用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'.
当location.path()
等于cookies.get()
时,undefined
的值永远不会改变。我想我是不是错误地使用了spyOn?
跟进我的模拟值:
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
?
答案 0 :(得分:2)
现在,您正在测试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
,您应该测试的是,无论函数调用您问题中的第一位代码是做正确的事情。