Angular 2/4/6/7 - Unit Testing with Router

后端 未结 4 875

In Angular 2.0.0, I am unit testing a component that uses Router. However I get the \'Supplied parameters do not match any signature of call target.\' error. In Visual studi

4条回答
  •  难免孤独
    2020-11-27 14:36

    You can also just use the RouterTestingModule and just spyOn the navigate function like this...

    import { TestBed } from '@angular/core/testing';
    import { RouterTestingModule } from '@angular/router/testing';
    import { Router } from '@angular/router';
    
    import { MyModule } from './my-module';
    import { MyComponent } from './my-component';
    
    describe('something', () => {
    
        let fixture: ComponentFixture;
        let router: Router;
    
        beforeEach(() => {
    
            TestBed.configureTestingModule({
                imports: [
                    MyModule,
                    RouterTestingModule.withRoutes([]),
                ],
            }).compileComponents();
    
            fixture = TestBed.createComponent(MyComponent);
            router = TestBed.get(Router);
    
        });
    
        it('should navigate', () => {
            const component = fixture.componentInstance;
            const navigateSpy = spyOn(router, 'navigate');
    
            component.goSomewhere();
            expect(navigateSpy).toHaveBeenCalledWith(['/expectedUrl']);
        });
    });
    

提交回复
热议问题