如何使用jasmine测试window.location.href

5
这是我的控制器代码。
$scope.loadApplications = function () {
      var cacheKey = { key: cacheKeys.appList() };
      dataFactory.get("/Application/All", { cache: cacheKey })
             .then(function (result) {
                 $scope.count++;                     
                 $scope.applications = result.data.data;
                 $scope.filteredApplicationsList = $scope.applications;
                  if ($scope.applications.length===0){
                     $window.location.href = '/Account/WelCome'
                 }
                 else {
                     $scope.isLoad = true;
                  }

             });
  };

这是我针对以上函数编写的Jasmine测试用例:

  it('should redirect to welcome page', function () {
        scope.applications = {};
        scope.loadApplications();
        expect(window.location.href).toContain('/Account/WelCome');
    });

但它正在获取浏览器的当前URL,因此会引发错误。
Expected 'http://localhost:49363/Scripts/app/test/SpecRunner.html' to contain '/Account/WelCome'.

请问有谁可以告诉我如何测试 URL?


2个回答

7

最好使用$windows服务而不是window对象,因为它是一个全局对象。AngularJS总是通过$window服务引用它,所以它可能会被覆盖、删除或模拟测试。

describe('unit test for load application', function(){
  beforeEach(module('app', function ($provide) {
    $provide.value('$window', {
       location: {
         href: ''
       }
    });
  }));
  it('should redirect to welcome page', function ($window) {
     scope.applications = {};
     scope.loadApplications();
     expect($window.location.href).toContain('/Account/WelCome');
  });
});

我认为这不会起作用,因为beforeEach接受的是一个函数而不是一个模块。 - Shilpa

0

你应该以这种方式编写。

it('should redirect to welcome page', function () {
        scope.applications = {};
        scope.loadApplications();

        browser.get('http://localhost:49363/Account/WelCome');
        expect(browser.getCurrentUrl()).toEqual('whateverbrowseryouarexpectingtobein');
        expect(browser.getCurrentUrl()).toContain('whateverbrowseryouarexpectingtobein');

        //expect(window.location.href).toContain('/Account/WelCome');
    });

5
我认为原问题是关于单元测试的,而这个回答似乎在使用protractor,对吗? - Will Buck
我认为这个答案与端到端测试有关。 - SHIVAM JINDAL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接