【问题标题】:Unit test Angular router event on ActivationstartActivationstart 上的单元测试 Angular 路由器事件
【发布时间】:2021-05-27 10:38:22
【问题描述】:

在为下面提到的代码编写测试用例方面需要一些帮助。问题是,我无法模拟 ActivationStart。我正在使用角度 10。

this.router.events
  .pipe(
    filter((event) => event instanceof ActivationStart)
  )
  .subscribe((event) => {
    this.breadCrumb = this.getBreadCrumb(event);
    // other logics here
  });

【问题讨论】:

    标签: angular rxjs jasmine karma-jasmine


    【解决方案1】:

    我认为你可以利用RouterTestingModule

    试试这个:

    @Component({
      selector: 'dummy',
      template: '<div>Hello</div>,
      styleUrls: [],
    })
    class DummyComponent {}
    describe('YourComponent', () => {
      let router: Router;
       
      // waitForAsync is async in older versions of Angular
      beforeEach(waitForAsync(() => {
        TestBed.configureTestingModule({
          declarations: [
            DummyComponent,
            // your other declarations here
          ],
          imports: [
            RouterTestingModule.withRoutes([
              { path: 'dummy', component: DummyComponent },
            ]),
          ]
        }).compileComponents();
         
         router = TestBed.inject(Router); // TestBed.inject should be TestBed.get in older versions of Angular
         // wait for the initialNavigation of the router
         // I think this should be enough to trigger that event you require
         router.initialNavigation();
      }));
    
      it('should trigger the event', async () => {
         // this explicit navigation should trigger the event
         await router.navigate('dummy');
         // assert the breadcrumb
         expect(component.breadCrumb).toBe(...);
    
      });
    
    });
    

    【讨论】:

      猜你喜欢
      • 2022-06-23
      • 2021-04-26
      • 2013-12-24
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 2020-03-19
      • 2021-07-30
      相关资源
      最近更新 更多