单元测试窗口位置分配的角度问题

unit testing angular issue with window location assign

本文关键字:问题 分配 窗口 位置 单元测试      更新时间:2024-01-25

在我的ctrl中,我有这样的代码,可以在函数完成工作后导航到一个页面。

 $scope.myFunction = function(){
     //other code
     window.location.assign(url);
 }

我的测试代码如下所示。

   describe('TEST', function () {
      var window;
      beforeEach(module(function($provide) {  
       //dummy window    
       window = {            
           location:{href:function(){return 'dummy'},assign:function()
            {return 'dummy1'}}   
        };
       
         // We register our new $window instead of the old    
            $provide.constant('$window',window);
       
         }));
       it("should test",function(){
            $scope.myfunction();
       });
});
  The error that I get is ..Some of your tests did a full page reload! and the test fails.

我已经关注了这里记录的问题(单元测试AngularJS$window服务),但同样的方法对我不起作用。知道吗?

您的函数需要$window注入,而不是window

$scope.myFunction = function($window){
     //other code
     $window.location.assign(url);
 }

正如所写的,您绕过了模拟的$window服务,并对实际的本机窗口对象进行操作。