angularjs - 如何使用 jasmine 测试 $window.open

标签 angularjs jasmine karma-runner

这是我的功能

 $scope.buildForm = function (majorObjectId, name) {
      $window.open("/FormBuilder/Index#/" + $scope.currentAppId + "/form/" + majorObjectId + "/" + name);
  };

这是我的 Jasmine 测试规范
            it('should open new window for buildForm and with expected id', function () {
            scope.majorObjectId = mockObjectId;
            scope.currentAppId = mockApplicationId;
            var name = "DepartmentMajor";
            scope.buildForm(mockObjectId, name);
            scope.$digest();
            expect(window.open).toHaveBeenCalled();
            spyOn(window, 'open');
            spyOn(window, 'open').and.returnValue("/FormBuilder/Index#/" + scope.currentAppId + "/form/" + scope.majorObjectId + "/" + name);
        });

但是当我尝试运行它时,它正在打开一个新标签,我不希望这种情况发生,我只想检查给定的 returnValues 是否存在!

最佳答案

首先你的期望 (window.open).toHaveBeenCalled() 是在错误的地方。
在监视事件之前,您不能指望。
现在来回答你的问题
Jasmine 中有不同的方法可以监视依赖项,例如

  • .and.callThrough - 通过使用 and.callThrough 链接 spy , spy 仍将跟踪对其的所有调用,但此外它将委托(delegate)给实际的实现。
  • .and.callFake - 通过使用 and.callFake 链接 spy ,对 spy 的所有调用都将委托(delegate)给提供的函数。
  • .and.returnValue - 通过使用 and.returnValue 链接 spy ,所有对该函数的调用都将返回一个特定的值。

  • Please check Jamine doc for complete list



    根据您的要求,以下示例测试用例
    $scope.buildForm = function() {
            $window.open( "http://www.google.com" );
        };
    

    将会
    it( 'should test window open event', inject( function( $window ) {
            spyOn( $window, 'open' ).and.callFake( function() {
                return true;
            } );
            scope.buildForm();
            expect( $window.open ).toHaveBeenCalled();
            expect( $window.open ).toHaveBeenCalledWith( "http://www.google.com" );
        } ) );
    

    关于angularjs - 如何使用 jasmine 测试 $window.open,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31286162/

    相关文章:

    angular - [网络服务器] : 404:/@angular/core/testing, systemjs、 karma 、angular2、jspm

    javascript - 如何在复杂的资源加载序列中正确链接 promise ?

    javascript - 测试 AngularJs + Jasmine 时无法获取指令中的元素

    javascript - karma Jasmine 测试 : Highlight diff in terminal

    javascript - 如何在 Intellij 或 Webstorm 中使用 Karma & Jasmine 调试 JS 单元测试

    angularjs - 当没有 $scope 强制摘要时,如何解决 AngularJS、Jasmine 2.0 中的 promise ?

    javascript - 像 Jasmine 一样测试 Angular Controller

    javascript - 如何在 angularjs Controller 中进行 google place api 搜索

    javascript - angularjs 复选框验证至少两个

    gruntjs - Karma 无法启动 Firefox