业力 - 预期未定义为相等

时间:2015-12-15 12:27:35

标签: angularjs testing karma-jasmine

我有我的模拟窗口对象和方法:

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);
}

1 个答案:

答案 0 :(得分:1)

open函数this中指的是window对象,而不是函数本身,所以试试这个:

expect(window.href).toEqual("views/Box_Ladder.html");

此处有关this的更多信息:How does the "this" keyword work?

此外,您已根据文档使用callFake

  

Spies:andCallFake

     

通过使用andCallFake链接间谍,对间谍的所有调用都将委托给提供的函数。

您可以将您的实现注册为伪函数,也可以使用调用实际实现的callThrough(或之前已经模拟过的实现)。

您可以在Jasmine docs中找到所有详细信息:http://jasmine.github.io/