【问题标题】:AngularJS: unit testing ui-router state changesAngularJS:单元测试 ui-router 状态变化
【发布时间】:2015-06-16 13:36:37
【问题描述】:

我对角度单元测试还很陌生,所以请多多包涵!

我为我的应用设置了 $stateProvidor,并想测试路由部分是否正常工作。

假设我有这种配置:

angular.module("app.routing.config", []).config(function($stateProvider, $urlRouterProvider) {
  $stateProvider.state("home", {
    url: "/",
    templateUrl: "app/modules/home/page/home_page.html",
    controller: "HomePageController",
    resolve: {
      setPageTitle: function($rootScope) {
        return $rootScope.pageTitle = "Home";
      }
    }
  }).state("somethingelse", {
    url: "/",
    templateUrl: "app/modules/home/page/somethingelse.html",
    controller: "SomeThingElseController",
    resolve: {
      setPageTitle: function($rootScope) {
        return $rootScope.pageTitle = "Some Thing Else";
      }
    }
  });
  return $urlRouterProvider.otherwise('/');
});

我看到这个博客post 介绍了如何为 ui-router 配置设置单元测试,所以我尝试采用相同的方法,这是我正在尝试的测试:

'use strict';
describe('UI-Router State Change Tests', function() {
  var $location, $rootScope, $scope, $state, $templateCache;
  beforeEach(module('app'));
  beforeEach(inject(function(_$rootScope_, _$state_, _$templateCache_, _$location_) {
    $rootScope = _$rootScope_;
    $state = _$state_;
    $templateCache = _$templateCache_;
    $location = _$location_;
  }));
  describe('State Change: home', function() {
    beforeEach(function() {
      $templateCache.put(null, 'app/modules/home/page/home_page.html');
    });
    it('should go to the home state', function() {
      $location.url('home');
      $rootScope.$digest();
      expect($state.href('home')).toEqual('#/');
      expect($rootScope.pageTitle).toEqual('Home');
    });
  });
});

运行测试时,我在输出中收到此错误:

错误:意外请求:GET app/modules/home/page/home_page.html

显然我在这里做错了,所以任何帮助或指点将不胜感激。

我确实遇到了 $httpBackend,这是我也应该在这里使用的东西,所以告诉我的测试期待对我的状态更改测试正在发出的 html 页面的请求?

【问题讨论】:

    标签: angularjs unit-testing karma-jasmine


    【解决方案1】:

    这几乎可以肯定归结为在应用/测试运行时异步加载的部分 html 视图 (home_page.html)。

    为了处理这个问题,您可以将您的 html 部分预处理为 Javascript 字符串,然后可以通过您的测试同步加载。

    看看karma-ng-html2js-preprocessor 应该可以解决您的问题。

    【讨论】:

      猜你喜欢
      • 2016-06-03
      • 2018-07-22
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      相关资源
      最近更新 更多