angularjs - Angular JS - 使用 Karma/Jasmine 测试带有页面重定向的函数

标签 angularjs jasmine karma-runner karma-jasmine

我的 Angular Controller 中有一个如下所示的函数:

$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 总是返回未定义,我怀疑这是由 Angular 和 Jasmine 相互链接的方式引起的。

最佳答案

自从提出这个问题以来已经很长时间了,但是以下方法应该更清晰:

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

使用angular-mocks/ngMock ,类似:

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

应该允许测试通过,假设 Controller 不需要 $window 来做其他事情。

关于angularjs - Angular JS - 使用 Karma/Jasmine 测试带有页面重定向的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22390319/

相关文章:

javascript - 动态添加的 Angular Material 输入没有得到样式

javascript - 带有 ng-animate 的 ng-show 无法正常工作

javascript - AngularJS 将一个数组放入 $cacheFactory 中

resharper - Resharper 7 中的 Jasmine 和 Requirejs

javascript - 自定义 Jasmine 匹配器和 Protractor

Angular + (Jasmine/Karma) - 错误 : Illegal state: Could not load the summary for directive

javascript - Protractor 中 'it' block 内的同步

javascript - 使用 phantomjs headless 运行 jasmine 规范

angularjs - createSpy 如何在 Angular + Jasmine 中工作?

javascript - Angular 单元测试 : Calling a method defined in another controller is throwing 'undefined' is not an error