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

前端之家收集整理的这篇文章主要介绍了angularjs – Angular JS – 使用Karma / Jasmine测试页面重定向功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的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其他任何东西.

原文链接:https://www.f2er.com/angularjs/141777.html

猜你在找的Angularjs相关文章