Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

javascript - Router events not executing in unit test

I am trying to test my router.events, but the events are not triggering, and I am not sure why. I have tried this with no luck.

Here is how I have my test setup:

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let router: Router;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule, 
        RouterTestingModule.withRoutes([
          { path: Constants.routes.login, component: LoginComponent },
          { path: Constants.routes.admin.admin, component: AdminWelcomeComponent },
          { path: Constants.routes.user.user, component: HomeComponent }
        ])
      ]
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    router = TestBed.inject(Router);
  });


  it('should be created', () => {
    component.apps = [{ name: '', url: '/test' }];
    component.ngOnInit();

    const event = new NavigationEnd(42, '/test', '/test');
    (TestBed.inject(Router).events as Subject<Event>).next(event);
  });
});

As seen in this screenshot, the subscription is not executed.

missed lines

question from:https://stackoverflow.com/questions/65836894/router-events-not-executing-in-unit-test

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You also have to make sure that change detection is run:

/* ... */
fixture.detectChanges();

(TestBed.inject(Router).events as Subject<Event>).next(event);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...