【发布时间】:2016-07-06 17:35:07
【问题描述】:
我知道当您使用 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() 的值永远不会改变。我认为我错误地使用了 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?
【问题讨论】:
-
什么是
cookies?它从哪里来的?如果这应该模拟$cookies,那就错了。$cookies没有注入,cookies不是$cookies。 -
有一个捷径:
spyOn(cookies, 'get').and.returnValue(undefined); -
我添加了一个编辑来帮助澄清我的模拟。不确定这是否是您的意思,但我的代码中确实有这些模拟,只是没有显示。
标签: angularjs unit-testing jasmine