0

サービスは次のとおりです。

import { Injectable } from '@angular/core';
import { Router, Event, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';

@Injectable()
export class LoaderService {

  public shouldShowLoader: boolean = false;

  constructor(private router: Router) {
    router.events.subscribe((event: Event) => {
      this.navigationInterceptor(event);
    });
  }

    // Shows and hides the loading spinner during Event changes
    navigationInterceptor(event: Event): void {
        if (event instanceof NavigationStart) {
          this.shouldShowLoader = true;
        }
        else if (event instanceof NavigationEnd) {
          this.shouldShowLoader = false;
        }

        // Set loading state to false in both of the below events to hide the spinner in case a request fails
        else if (event instanceof NavigationCancel) {
          this.shouldShowLoader = false;
        }
        else if (event instanceof NavigationError) {
          this.shouldShowLoader = false;
        }
        else {
          this.shouldShowLoader = false;
        }
    }
}

失敗しているテストは次のとおりです。

import { TestBed, inject } from '@angular/core/testing';
import { Router } from '@angular/router';
import { LoaderService } from './loader.service';

describe('LoaderServiceTest', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [ LoaderService, Router ]
        });
    });
    
    it('#LoaderService should be defined', inject([LoaderService, Router], (service: LoaderService) => {
        expect(service).toBeDefined();
    }));

});

失敗する理由がわからない?同様の問題をグーグルで検索すると、Angular 2ベータ版の回答しか見つかりません...最新のAngular 2 / 2.2.0を使用しています

4

1 に答える 1

1

ルーターをインスタンス化するために必要なすべてのパラメーターをテスト モジュールに提供していないため、テストは失敗しています。そうは言っても、単体テストでは、ルーターのようなサービスの実際の実装を使用することはお勧めしません。より良い代替手段は、次のようなスタブを作成することです (関数がある時点で呼び出されたことを確認したい場合にどのように実行されるかを示すために、ルーター内に関数のスパイを追加しました)。

class RouterStub {
    navigateByUrl = jasmine.createSpy('navigateByUrl');
}

次に、テスト モジュールを構成するとき:

providers: [
    ...,
    { provide: Router, useClass: RouterStub }
]

モックと単体テストのセットアップの使用方法に関する詳細情報が必要な場合は、https ://angular.io/docs/ts/latest/guide/testing.html の公式ドキュメントを参照してください。

于 2016-12-05T16:16:09.957 に答える