PatrickJS-starter icon indicating copy to clipboard operation
PatrickJS-starter copied to clipboard

Unit test error: Router outlet is not a known element

Open gaurav2887 opened this issue 10 years ago • 14 comments

Note: for support questions, please use one of these channels: Chat: AngularClass.slack or Twitter: @AngularClass

  • I'm submitting a ... [x ] bug report

I am getting following error when running a unit test:

Error: Template parse errors: 'router-outlet' is not a known element: 1. If 'router-outlet' is an Angular component, then verify that it is part of this module.

My unit test code:


import {
    inject,
    TestBed
} from '@angular/core/testing';

// Load the implementations that should be tested
import { App } from './app.component';
import { AppState } from './app.service';
import { Renderer } from '@angular/core';
import { Router, RouterOutlet } from "@angular/router";

class MockRouter { public navigate() {}; }

describe('App', () => {

    // provide our implementations or mocks to the dependency injector
    beforeEach(() => TestBed.configureTestingModule({
        declarations: [ App ],
        providers: [
            AppState,
            Renderer,
            {provide: Router,  useClass: MockRouter },
            RouterOutlet
        ]}));

    it('should have a url', inject([ App ], (app: App) => {
        expect(app.name).toEqual('test');
    }));

});

My app.html has router outlet:

        <router-outlet></router-outlet>

I tried removing RouterOutlet as well in unit test and it did not work. Has anyone experienced this issue and help me with the solution?

gaurav2887 avatar Sep 14 '16 21:09 gaurav2887

I resolved this by importing RouterModule in spec file.

gaurav2887 avatar Sep 16 '16 16:09 gaurav2887

That didn't work for me (using 2.0.0). What worked for me was importing RouterTestingModule instead.

eamell avatar Sep 16 '16 16:09 eamell

@eamell - I am still on rc6 and I changed my configuration to RouterTestingModule and it still works. Thanks for the help as this will not break my tests when I will move to 2.0.0

I am doing it this way now. Is that correct?

import {
    RouterTestingModule
} from '@angular/router/testing';

  beforeEach(() => {

        TestBed.configureTestingModule({
            providers: [
                App,
                AppState,
                Renderer,
                {provide: Router,  useClass: MockRouter }
            ],
            imports: [ RouterTestingModule ]
        });

    });

gaurav2887 avatar Sep 16 '16 20:09 gaurav2887

Hi @eamell,

I tried importing RouterTestModule in my spec file but just end up getting another error.

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [
                AppComponent
            ],
            providers: [
                // Other provides...
                { provide: Router, useClass: class { navigate = jasmine.createSpy("navigate"); } }
            ],
            imports: [
                // Other modules...
                RouterTestingModule
            ]
        });

    }));

Error message I got: Cannot read property 'root' of undefined.

It looks like it was trying to evaluate: router.RouterState.root. Am I missing something here?

Thanks!

randyangeles avatar Sep 18 '16 23:09 randyangeles

Hi @randyangeles,

If you are trying to setup routes you need to provide the routes in your import and unless I am mistaken importing RouterTestingModule takes care of mocking Router for you. You would need to do something like the following:

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      imports: [
           RouterTestingModule.withRoutes({_route here_})
      ]
    });

    fixture = TestBed.createComponent(AppComponent);
    app = fixture.debugElement.componentInstance;
  });

You can then create routes to actual or mock components within your test. In my case the routing is really simple (I really only use routing to make it easy to get info from the URL and for future support) so I actually removed the routing and only include the core import at the moment.

Take a look at the documentation (which unfortunately still appears to be a work in progress) for more information (https://angular.io/docs/ts/latest/api/router/testing/index/RouterTestingModule-class.html).

Hope this helps!

eamell avatar Sep 19 '16 12:09 eamell

Hi @gaurav2887,

Just saw your post. As I mentioned to @randyangeles, I don't think you should be mocking the router rather use the withRoutes function when importing RouterTestingModule. That way you can route to either your actual components or to mock components. My hope is that using this approach we will be less susceptible to framework changes going forward.

Hope that helps!

eamell avatar Sep 19 '16 12:09 eamell

Hi @eamell,

Tried your approach and it worked! Going to leave what I did here to help someone down the road hopefully.

    @Component({
        template:''
    })
    class MockLoginComponent { }

    @NgModule({
        declarations: [MockLoginComponent],
        exports:      [MockLoginComponent]
    })
    class MockModule { }

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [
                AppComponent
            ],
            providers: [
                //...
            ],
            imports: [
                MockModule,
                RouterTestingModule.withRoutes([
                    {
                        path: 'login',
                        component: MockLoginComponent
                    }
                ]),
            ]
        });
    }));

    it(...
       spyOn(appComponent.router, 'navigate');
       expect(appComponent.router.navigate).toHaveBeenCalledWith(['/login']);
       expect(appComponent.router.navigate).toHaveBeenCalledTimes(1);
    );

Had to make the router public in AppComponent to be able to spy on it (not sure if that's best practice). Thanks for your help!

randyangeles avatar Sep 20 '16 17:09 randyangeles

@eamell - Thanks.

One of my test case is breaking with RouterTestingModule as following code do not set router url property value to 'help'.

spyOn(app.router, 'navigate'); app.router.navigate(['/help']);

I have a function which is using "this.router.url.indexOf(route) > 0" logic and I want to test that by mocking the url.

router.navigate does not set the url property. How can mock router.url?

gaurav2887 avatar Sep 22 '16 04:09 gaurav2887

I tried make testing with different inject but the principal problem es that the router is not recognized. somebody can I help with what I have that add into describe or in other site.

import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component'; import { SearchComponent } from './search/search.component';

@NgModule({ declarations: [ AppComponent, SearchComponent ], imports: [ BrowserModule, FormsModule, HttpModule, RouterModule.forRoot([ { path: '', component: SearchComponent }, ]) ], providers: [], bootstrap: [AppComponent] })

export class AppModule { }


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

@Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.css'], }) export class SearchComponent implements OnInit {

constructor() { }

ngOnInit() { }

}


describe('Component: Search', () => { it('should create an instance de router', () => { beforeEach(() => { TestBed.configureTestingModule({ declarations: [ SearchComponent, RouterModule ] }); });


Error: 'router-outlet' is not a known element:
1. If 'router-outlet' is an Angular component, then verify that it is part of this module.
2. If 'router-outlet' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("

[ERROR ->]"): AppComponent@6:0

boraita avatar Oct 26 '16 14:10 boraita

Posts deleted & reported.

joshwiens avatar Dec 01 '16 04:12 joshwiens

i resolved it by adding "routing " to imports: (Ngmodule)

ajithvcoder avatar Feb 15 '17 18:02 ajithvcoder

I try to add "RouterModule" to the @Ngmodule.
It worked! Thanks! @ajithvallabai

pomelos7ca avatar Jun 05 '17 15:06 pomelos7ca

import {NgModule, Component} from '@angular/core'; import { ToasterService} from 'angular2-toaster'; import { ToastComponent } from 'angular2-toaster/angular2-toaster'; import { ToasterModule } from 'angular2-toaster'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import { RouterOutlet, RouterModule } from '@angular/router';

@NgModule({ imports: [BrowserAnimationsModule, ToasterModule, RouterModule], declarations: [TestComponent], providers: [], bootstrap: [TestComponent] })

@Component({ selector: 'root', template: <toaster-container></toaster-container> <button (click)="popToast()">pop toast</button>,

providers: [ToasterService] })

export class TestComponent { private toasterService: ToasterService;

constructor(toasterService: ToasterService) { this.toasterService = toasterService; }

popToast() { this.toasterService.pop('success', 'Args Title', 'Args Body'); } }

Above is my code and I'm still getting the below error....

Uncaught Error: Template parse errors: 'toaster-container' is not a known element:

  1. If 'toaster-container' is an Angular component, then verify that it is part of this module.
  2. If 'toaster-container' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (".....

Any help is appreciated.

Note: I have installed Angular 4 in m y machine.

kam1515 avatar Aug 11 '17 23:08 kam1515

It's easy to miss the correct solution in the thread. @eamell solution of adding RouterTestingModule is the correct one. More details can be found at https://github.com/mrholek/CoreUI-Free-Bootstrap-Admin-Template/issues/202#issuecomment-316686130

duluca avatar Sep 27 '17 13:09 duluca