Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Router events triggered unexpectedly when a component is rendered #318

Closed
ruoxin-mx51 opened this issue Nov 2, 2022 · 5 comments
Closed

Comments

@ruoxin-mx51
Copy link

The router events will be trigger when a component is rendered.

Given a component

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-apple',
  templateUrl: './apple.component.html',
  styleUrls: ['./apple.component.css'],
})
export class AppleComponent implements OnInit {
  constructor(private router: Router) {}

  ngOnInit(): void {
    this.router.events.subscribe((event) => {
      console.log(event);
    });
  }
}

and its test

import { AppleComponent } from './apple.component';
import { render, screen } from '@testing-library/angular'
import { RouterTestingModule } from '@angular/router/testing';

describe('AppleComponent', () => {
  it('should have "apple works!"', async () => {
    await render(AppleComponent, {
      declarations: [AppleComponent],
      imports: [RouterTestingModule]
    })
    expect(screen.getByText('apple works!'));
  });
});

Now run the test then you can see the router events (which won't show up with Angular TestBed or when running the app)

Is this an intentional behaviour? (FYI I believe this behaviour was introduced in version 11.0.3: #286)

@timdeschryver
Copy link
Member

This is an intended behavior to reflect a "running" application.

I would suspect the running app to behave the same way though, maybe it isn't because event would already be processed? I'll have to investigate this, perhaps it would be better to invoke the initialNavigation() method before the component is created.

@ruoxin-mx51
Copy link
Author

Thanks for reply. I have tested it in a running app but didn't see this behaviour. This is the repo: https://github.com/ruoxin-mx51/ng14-apple-banana

@timdeschryver
Copy link
Member

Thanks @ruoxin-mx51, this will get fixed soon.

@github-actions
Copy link

🎉 This issue has been resolved in version 13.0.0-beta.2 🎉

The release is available on:

Your semantic-release bot 📦🚀

@github-actions
Copy link

🎉 This issue has been resolved in version 13.0.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants