Skip to content

Router events triggered unexpectedly when a component is rendered #318

Closed
@ruoxin-mx51

Description

@ruoxin-mx51

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)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions