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

时间:2015-07-09 04:56:21

标签: angularjs jasmine karma-runner

这是我的控制器代码

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

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

Expected 'http://localhost:49363/Scripts/app/test/SpecRunner.html' to contain '/Account/WelCome'.

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

ng-repeat

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

2 个答案:

答案 0 :(得分: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');
  });
});

答案 1 :(得分:1)

你应该这样写。

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');
    });