Angular testing router params breaks test bed

后端 未结 3 1361
忘掉有多难
忘掉有多难 2021-02-06 21:58

When I provide params to my TestComponent the test bed blows up if the html contains a [routerLink]

testbed setup



        
3条回答
  •  故里飘歌
    2021-02-06 22:48

    This works with no errors and no hack

    import {
        TestBed,
        async
    } from '@angular/core/testing';
    import {
        HttpModule,
        BaseRequestOptions,
        Http
    } from '@angular/http';
    import { APP_BASE_HREF } from '@angular/common';
    import {
        RouterModule,
        ActivatedRoute
    } from '@angular/router';
    import { MockBackend } from '@angular/http/testing';
    import { Observable } from 'rxjs';
    import { Component } from '@angular/core';
    fdescribe( 'AppComponent', () => {
        beforeEach( () => {
            TestBed.configureTestingModule( {
                imports      : [
                    HttpModule,
                    RouterModule.forRoot(
                        [
                            {
                                path      : '',
                                component : TestComponent
                            }
                        ] )
                ],
                declarations : [ TestComponent ],
                providers    : [
                    BaseRequestOptions,
                    MockBackend,
                    {
                        provide    : Http,
                        useFactory : function ( backend : MockBackend, defaultOptions : BaseRequestOptions ) {
                            return new Http( backend, defaultOptions );
                        },
                        deps       : [ MockBackend, BaseRequestOptions ]
                    },
                    {
                        provide  : APP_BASE_HREF,
                        useValue : '/'
                    },
                    {
                        provide  : ActivatedRoute,
                        useValue : {
                            params : Observable.of( { versionId : '1' } ),
                            parent : {
                                params : Observable.of( { uniqueId : '1234' } )
                            }
                        }
                    }
                ]
            } );
            TestBed.compileComponents();
        } );
        it( 'should create the app', async( () => {
            let fixture = TestBed.createComponent( TestComponent );
            let app     = fixture.debugElement.componentInstance;
            expect( app ).toBeTruthy();
        } ) );
    } );
    
    @Component( {
        selector    : 'app-root',
        template : `
            Back
            
    
    `,
    } )
    export class TestComponent {
    
    }
    

提交回复
热议问题