如何测试$ window.open使用茉莉花 [英] how to test $window.open using jasmine

查看:226
本文介绍了如何测试$ window.open使用茉莉花的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的功能

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

这是我的茉莉花测试规范

This is my jasmine test spec

            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​​是否present都没有!

but when i try to run this it is opening a new tab and i don't want this to happen, i just want to check whether the given returnValues are present are not!!

推荐答案

您所有的期望(window.open)首先.toHaveBeenCalled()是在错误的地方。
你不能在间谍事件之前预期。
现在来到你的问题
有茉莉不同的方法来刺探的依赖,像

First of all your expectation (window.open).toHaveBeenCalled() is in wrong place. You cannot expect before spying the event. Now coming to your question there are different methods in jasmine to spy on dependencies,like


  • .and.callThrough - 通过链接与and.callThrough间谍,间谍还是会追踪到它的所有电话,但除了它会委托给实际执行

  • .and.callFak​​e - 通过链接与and.callFak​​e间谍,以间谍所有呼叫都将委托给提供的函数

  • .and.returnValue - 通过链接与and.returnValue间谍,给函数的所有调用将返回一个特定的值

  • .and.callThrough - By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation.
  • .and.callFake - By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function.
  • .and.returnValue - By chaining the spy with and.returnValue, all calls to the function will return a specific value.

请检查 Jamine DOC 获得完整列表

样测试用例低于按您的要求。

Sample test case for below as per your requirement

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

这篇关于如何测试$ window.open使用茉莉花的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆