我有我的模拟窗口对象和方法:
var window = {
open: function (url, target, specs) {
var spec, specKey;
this.href = url;
this.target = target;
// Parse through the spec string to grab the parameters you passed through
var specArray = specs.split(',');
for (specKey in specArray) {
spec = specArray[specKey].split('=');
this[String.trim(spec[0])] = String.trim(spec[1]);
}
}
};
和我的测试用例:
describe('$scope.popup1', function () {
it('should open a popup window when ISIN hyperlink is clicked within grid, passing ISIN object s values to shareDataService', inject(function ($window) {
spyOn($window, 'open').and.callFake(function () {
return true;
});
scope.popup1()
expect(window.open).toHaveBeenCalled();
expect(window.open.href).toEqual("views/Box_Ladder.html");
})
)
})
但我得到 Expected undefined to equal 'views/Box_Ladder.html'
。我不确定我上面声明的 window.open.href 是如何未定义的?
编辑 - 更新代码,仍然是同样的错误:
describe('mainCtrl', function () {
beforeEach(module('app'));
var controller, scope;
var window = {
open: function (url, target, specs) {
console.log("function being called")
var spec, specKey;
this.href = url;
this.target = target;
// Parse through the spec string to grab the parameters you passed through
var specArray = specs.split(',');
for (specKey in specArray) {
spec = specArray[specKey].split('=');
this[String.trim(spec[0])] = String.trim(spec[1]);
}
}
};
beforeEach(inject(function ($controller, $window, $rootScope) {
scope = $rootScope.$new();
controller = $controller('mainCtrl', {$scope: scope});
window = $window;
}));
describe('$scope.popup1', function () {
it('should open a popup window when ISIN hyperlink is clicked within grid, passing ISIN object s values to shareDataService', inject(function ($window) {
spyOn($window, 'open').and.callThrough()
scope.popup1()
expect(window.open).toHaveBeenCalled();
expect(window.href).toEqual("views/Box_Ladder.html");
//expect(window.location.target).toEqual("_blank");
//expect(window.location.height).toEqual(400);
//expect(window.width).toEqual(700);
})
)
})
});
和 popup1() 函数:
$scope.popup1 = function (isinData) {
var popup1 = window.open("views/Box_Ladder.html", "_blank",
"height = 400, width = 700");
shareDataService.setIsinClickValue(isinData);
}
最佳答案
在 open
函数中 this
指的是 window
对象,而不是函数本身,所以试试这个:
expect(window.href).toEqual("views/Box_Ladder.html");
关于这个
的更多信息在这里:How does the "this" keyword work?
此外,您还使用了 callFake
,根据文档,它是:
Spies: andCallFake
By chaining the spy with andCallFake, all calls to the spy will delegate to the supplied function.
您可以将您的实现注册为假函数,也可以使用 callThrough
来调用真正的实现(或您之前模拟过的实现)。
您可以在 Jasmine 文档中找到所有详细信息:http://jasmine.github.io/
关于angularjs - Karma - 预期未定义等于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34289307/