Search code examples
angularunit-testingeventsjestjs

angular detectChanges() unit testing


Hello developers I have a login component and I want to test it in the routing module and I'm using detectChanges() method my code looks like this:

describe('TEST: RoutingModule', () => {
let appComponent: AppComponent;
let loginComponent: LoginComponent;


let appComponentFixture: ComponentFixture<AppComponent>
let loginComponentFixture : ComponentFixture<LoginComponent>;


let router: Router;
let location: Location;

beforeEach(async () => {
    await TestBed.configureTestingModule({
        declarations: [AppComponent,LoginComponent],
        providers: [MockProvider(CookieService), MockProvider(Store), MockProvider(Router)],
        imports: [RouterTestingModule.withRoutes(AppRoutes.getStatics())]
    }).compileComponents(); 
});

beforeEach(() => {
    router = TestBed.inject(Router);
    location = TestBed.inject(Location);
    
    loginComponentFixture = TestBed.createComponent(LoginComponent);
    loginComponent = loginComponentFixture.componentInstance;
    loginComponentFixture.detectChanges(); // here I get error
    
    appComponentFixture = TestBed.createComponent(AppComponent);
    appComponent = appComponentFixture.componentInstance;
    router.initialNavigation();
});

then I get this error:

  TypeError: Cannot read properties of undefined (reading 'subscribe')

  43 |      public ngOnInit(): void {
  44 |              this.fromUrl();
> 45 |              const router$ = this.router.events.subscribe(event => {
     |                                                 ^
  46 |                      if (event instanceof NavigationEnd) {
  47 |                              this.fromUrl();
  48 |                      }

Solution

  • Try removing this: MockProvider(Router) in the providers array. You have RouterTestingModule in the imports array and this will mock the Router for you in a fake way. No need to mock it again with MockProvider(Router).