【问题标题】:AngularJS Karma check url param is presentAngularJS Karma 检查 url 参数是否存在
【发布时间】:2018-04-10 06:20:23
【问题描述】:

我是单元测试新手,正在尝试为我的应用编写单元测试。我的路线是:

{
    name: 'details',
    url: '/accounts/company/:companyId',
    controller: 'controllere',
    templateUrl: 'templateurl',
}

我的控制器:

if (!$stateParams.companyId) {
    $scope.promise = $state.go('home');
} else {
    // get company details
}

在我的单元测试中,我需要测试 URL 中是否存在“companyId”,然后只进行其余的重定向到“home”。我试过这段代码,但每次都失败。我不知道我做错了什么。

it('should respond to URL with params', function() {
    expect($state.href('/accounts/company/', { companyId: 'test-company' })).toEqual('#/accounts/company/test-company');
});

每次我运行这个测试时,它都会说:Expected null to equal '#/accounts/company/test-company'。

【问题讨论】:

    标签: angularjs unit-testing karma-jasmine karma-webpack


    【解决方案1】:

    $state.href 方法需要 stateName 作为第一个参数,后面的参数需要形成 URL,并且您在其中传递了状态 URL,这是错误的。

    expect(
       $state.href('details', { 
          companyId: 'test-company' 
       })
    ).toEqual('#/accounts/company/test-company')
    

    我发现您对该功能进行单元测试的方法有问题,应该以不同的方式进行测试。就像你应该首先从测试用例中调用底层方法并检查你是否得到了想要的结果。

    控制器

    function redirect() {
      if (!$stateParams.companyId) {
        $scope.promise = $state.go('home');
      } else {
        // get company details
      }
    }
    $scope.redirect = redirect;
    

    spec.js

    //test pseudo code
    describe('should redirect correctly', function(){
       it('should redirect to details page when companyId is passed', function(){
          //arrange
          //TODO: please make sure, you avail useful dependency before using them  
          var $scope = $rootScope.$new(),
              mockParams = { companyId: 1 }
          $controller('myCtrl', {$scope: $scope, $stateParams: mockParams });
    
          //assert
          $scope.redirect();
    
          //act
          $scope.$apply(); //apply the changes
          expect($state.current.url).toEqual('#/accounts/company/test-company');
    
       })
    })
    

    【讨论】:

    • 谢谢@Pankaj Parker。现在它没有显示错误。你认为我在做正确的单元测试吗?如果为真,我是否需要测试这两个条件,然后继续重定向到“家”。我不知道该怎么做。
    • @pkdq 我认为它不正确,请查看更新后的答案。
    • 帕克它说 $scope.redirect();不是函数。
    • @pkdq 我写了伪代码,这可能是你代码中的其他内容。我调用$scope.redirect 的意思是,调用重定向逻辑并期望 URL 会更改为所需的。请用你的代码映射我的伪代码。
    • Parker 感谢您的帮助,但我仍然不明白如何完成这项工作。我今天对此很陌生,只是我开始摸不着头脑。
    猜你喜欢
    • 2011-07-18
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多