簡體   English   中英

Angular 單元測試 router.events

[英]Angular Unit test router.events

我有一個組件可以更新特定路由器事件的變量。 我如何進行單元測試以確保下面的代碼正常工作?

router.events.subscribe(event => {
  if (event instanceof NavigationStart) {
    this.isLoading = true;
  } else if (event instanceof NavigationEnd || event instanceof NavigationCancel) {
    this.isLoading = false;
  } else if (event instanceof NavigationError) {
    this.isLoading = false;
    // console.error('effect error: ', error);
  }
});

路由器存根

class MockRouter {
    navigate = jasmine.createSpy('navigate');
    start = new NavigationStart(0, '/home');
    end = new NavigationEnd(1, '/home', '/dashboard');
    events = new Observable(observer => {
      observer.next(this.start);
      observer.next(this.end);
      observer.complete();
    });
  }

我遇到了類似的情況,這就是我想出來的:

describe('router.events', () => {
  const mockStart = of(new NavigationStart(0, '/testUrl'));
  const mockEnd = of(new NavigationEnd(0, '/testUrl', '/testUrlRedirect'));
  const mockCancel = of(new NavigationCancel(0, '/testUrl', '/testReason'));
  const mockError = of(new NavigationError(0, '/testUrl', 'test error'));

  let routerEventSpy: jasmine.Spy;
  beforeEach(() => {
    routerEventSpy = spyOn(component.router, 'events');
  });

  it('should set isLoading to true', () => {
    // Arrange
    routerEventSpy.and.returnValue(mockStart);
    component.isLoading = false; // initial value to make sure code is effective

    // Act
    // Call whatever method contains your router.events.subscribe - for example:
    component.ngOnInit(); // <-- Just an example, you should replace this with your corresponding method

    // Assert
    expect(component.isLoading).toBe(true);
  });

  it('should set isLoading to false for NavigationEnd', () => {
    // Arrange
    routerEventSpy.and.returnValue(mockEnd);
    component.isLoading = true; // initial value, see first test

    // Act
    // Call whatever method contains your router.events.subscribe - for example:
    component.ngOnInit(); // <-- Just an example, see first test

    // Assert
    expect(component.isLoading).toBe(false);
  });

  it('should set isLoading to false for NavigationCancel', () => {
    // Arrange
    routerEventSpy.and.returnValue(mockCancel);
    component.isLoading = true; // initial value, see first test

    // Act
    // Call whatever method contains your router.events.subscribe - for example:
    component.ngOnInit(); // <-- Just an example, see first test

    // Assert
    expect(component.isLoading).toBe(false);
  });

  it('should set isLoading to false for NavigationError', () => {
    // Arrange
    routerEventSpy.and.returnValue(mockError);
    component.isLoading = true; // initial value, see first test

    // Act
    // Call whatever method contains your router.events.subscribe - for example:
    component.ngOnInit(); // <-- Just an example, see first test

    // Assert
    expect(component.isLoading).toBe(false);
  });
});

一些注意事項:

  • component應該替換為您存儲fixture.componentInstance任何內容。這是您測試中的this
  • 這與路由器就像你在上面存根,但不使用,仍能正常工作Observable的-和它的方法,您已經聲明spy正在恢復of觀測來觸發subscribe 可能有一種方法可以將路由器存根用於您的目的(例如isLoading的回答),但您的問題只要求一種測試該邏輯和isLoading變量的方法。
  • 如果您的路由器是protectedprivate (一個很好的做法),您仍然可以使用括號表示法對其進行監視 - 例如spyOn(component['router'], 'events')

您需要創建一個簡單的路由器存根以允許在測試期間發出各種路由器事件。

路由器存根:

// mocked source of events
const routerEventsSubject = new Subject<RouterEvent>();

const routerStub = {
    events: routerEventsSubject.asObservable()
};

describe('FooComponent', () => {
    ...

然后您只需使用該存根:

...
let router: Router;

beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [
            {
                provide: Router,
                useValue: routerStub
            }
        ]
    });
    router = TestBed.inject(Router);
...

測試如下所示:

it('should be loading on a navigation start', () => {
    // create a navigation event
    routerEventsSubject.next(new NavigationStart(1, 'start'));

    expect(component.isLoading).toBeTruthy();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM