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

Sye*_*eed 4 jasmine angularjs karma-runner

这是我的控制器代码

$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;
                  }

             });
  };
Run Code Online (Sandbox Code Playgroud)

这是我对上述功能的茉莉花测试用例

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

但它正在获取浏览器的当前URL,并且它正在引发错误

Expected 'http://localhost:49363/Scripts/app/test/SpecRunner.html' to contain '/Account/WelCome'.
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我如何测试网址?

小智 5

最好使用$ 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');
  });
});
Run Code Online (Sandbox Code Playgroud)


RIY*_*HAN 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');
    });
Run Code Online (Sandbox Code Playgroud)

  • 我认为最初的问题是关于单元测试的,这个答案看起来是使用量角器,不是吗? (5认同)