加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – Angular JS – 使用Karma / Jasmine测试页面重定向

发布时间:2020-12-17 07:22:23 所属栏目:安全 来源:网络整理
导读:我的Angular控制器中有一个函数,如下所示: $scope.myFunction = function(){ $scope.myVariable = "something"; $scope.myOtherVariable = "something else"; window.location.href = "/path/to/page"; } 一个简单的Jasmine测试涵盖了上述功能,看起来像: d
我的Angular控制器中有一个函数,如下所示:
$scope.myFunction = function(){
    $scope.myVariable = "something";
    $scope.myOtherVariable = "something else";
    window.location.href = "/path/to/page"; 
}

一个简单的Jasmine测试涵盖了上述功能,看起来像:

describe('my test',function(){
    it('should pass',function(){
        scope.myFunction();
        expect(scope.myVariable).toBe('something');
        expect(scope.myOtherVariable).toBe('something else');     
    });
});

上面的测试本身通过,但随后Karma在控制台中抛出以下错误:

Some of your tests did a full page reload!

页面重定向导致Karma引发此警告.什么是最好的解决方法?

我想在Jasmine测试中给出匿名函数和Angular名称,然后在原始函数中使用arguements.callee.caller.name来确定函数是自己调用还是Jasmine调用.不幸的是,arguments.callee.caller.name总是返回undefined,我怀疑它是由Angular和Jasmine相互链接的方式引起的.

问这个问题已经很久了,但是下面的方法应该更清洁:

通过更改原始函数以使用Angular的$window服务而不是浏览器窗口对象,可以编写不需要修改生产代码或考虑任何运行时参数的测试.这当然要求$window是找到函数的控制器的依赖项.

使用angular-mocks/ngMock,类似于:

var fakeWindow = {
  location: {
    href: ''
  }
}
// instantiate controller with mock window
beforeEach(inject(function($controller) {
  $controller('YourCtrlName',{
    $window: fakeWindow
  });
}));

应该允许测试通过,假设控制器不需要$window其他任何东西.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读