【问题标题】:UI Router resolve throws Unexpected Get request in AngularUI 路由器解析在 Angular 中抛出 Unexpected Get 请求
【发布时间】:2015-07-13 19:14:56
【问题描述】:

我正在使用 UI 路由器并定义站点范围的解析。

$stateProvider
  .state('site', {
    abstract: true,
    resolve: {
      exampleResolve: function(MyApiService) {
        return MyApiService.get();
      }
    },
    views: {
      'site': {
        template: '<ui-view/>'
      }
    }
  })

但是,我有一个自定义指令,当我对其进行单元测试时,我收到“错误:意外请求:GET /api/example”(即“MyApiService.get()”)。

it('should do something', function() {
  scope.example.data = '123';
  scope.$digest();
  element.triggerHandler('blur');
  console.log(element);
})

不知何故抛出Error: Unexpected request: GET /api/example

【问题讨论】:

    标签: angularjs unit-testing angular-ui-router


    【解决方案1】:

    尝试模拟 MyApiService,以便调用不应委托给实际实现。

    it( 'should do something', inject( function( MyApiService ) {
    spyOn( MyApiService, 'get' ).and.callFake( function() {
        return true;
    } );
    scope.example.data = '123';
    scope.$digest();
    element.triggerHandler( 'blur' );
    console.log( element );} ) );
    

    【讨论】:

      【解决方案2】:

      您需要在测试用例中实例化服务,如下所示。

      //you need to inject dependencies first
      beforeEach(inject(function(MyApiService) {
          MyApiService.get();        
      }));
      

      【讨论】:

        【解决方案3】:
        try to mention <ui-view/> in HTML
        //HTML
        <body>
        <div ui-view="site"></div>
        </body>
        
        //Javascript
        $stateProvider
        .state('sites',{
        views: {
          'site': {
            templateUrl: 'sites-site.html',
            controller: function($scope){ ... controller stuff just for site view ..}     
        
          }
        }
        })
        

        【讨论】:

          猜你喜欢
          • 2017-03-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-11-18
          • 1970-01-01
          • 2017-07-04
          • 2016-04-16
          • 1970-01-01
          相关资源
          最近更新 更多