Angular 2/4/6/7 - 使用路由器进行单元测试

问题描述 投票:38回答:4

在Angular 2.0.0中,我正在测试使用Router的组件。但是我得到'提供的参数与呼叫目标的任何签名都不匹配'。错误。在spec.ts中的Visual Studio代码中,新的Router()以红色突出显示

如果有人能让我知道正确的语法是什么,我真的很感激?提前致谢。我的代码如下:

spec.ts

import { TestBed, async } from '@angular/core/testing';
import { NavToolComponent } from './nav-tool.component';
import { ComponentComm } from '../../shared/component-comm.service';
import { Router } from '@angular/router';

describe('Component: NavTool', () => {
  it('should create an instance', () => {
    let component = new NavToolComponent( new ComponentComm(), new Router());
    expect(component).toBeTruthy();
  });
});

组件构造函数

constructor(private componentComm: ComponentComm, private router: Router) {}
angular unit-testing angular6 karma-jasmine angular7
4个回答
85
投票

您也可以使用RouterTestingModule,只需像这样窥探导航功能......

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<LandingComponent>;
    let router: Router;

    beforeEach(() => {

        TestBed.configureTestingModule({
            imports: [
                MyModule,
                RouterTestingModule.withRoutes([]),
            ],
        }).compileComponents();

        fixture = TestBed.createComponent(MyComponent);
        router = TestBed.get(Router)

    });

    it('should navigate', () => {
        let component = fixture.componentInstance;
        let navigateSpy = spyOn(router, 'navigate');

        component.goSomewhere();
        expect(navigateSpy).toHaveBeenCalledWith(['/expectedUrl']);
    });
});

20
投票

这是因为Route有一些它期望传递给它的构造函数的依赖项。

如果您使用的是Angular组件,则不应该尝试进行隔离测试。您应该使用Angular测试基础结构来准备测试环境。这意味着让Angular创建组件,让它注入所有必需的依赖项,而不是尝试创建所有内容。

为了让你开始,你应该有类似的东西

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

describe('Component: NavTool', () => {
  let mockRouter = {
    navigate: jasmine.createSpy('navigate')
  };
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ NavToolComponent ],
      providers: [
        { provide: Router, useValue: mockRouter },
        ComponentComm
      ]
    });
  });
  it('should click link', () => {
    let fixture = TestBed.createComponent(NavToolComponent);
    fixture.detectChanges();
    let component: NavToolComponent = fixture.componentInstance;
    component.clickLink('home');
    expect(mockRouter.navigate).toHaveBeenCalledWith(['/home']);
  });
});

或类似的东西。您可以使用TestBed从头开始配置模块以进行测试。您使用@NgModule以几乎相同的方式配置它。

这里我们只是嘲笑路由器。由于我们只是单元测试,我们可能不需要真正的路由设施。我们只是想确保使用正确的参数调用它。模拟和spy将能够捕获我们的电话。

如果您确实想使用真实路由器,那么您需要使用RouterTestingModule,您可以在其中配置路由。查看示例herehere

也可以看看:


1
投票

对于完整的间谍物体,Jasmine更好一点......

describe(..., () => {
    const router = jasmine.createSpyObj('Router', ['navigate’]);
    ...
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            providers: [  { provide: Router, useValue: router } ],
            ...
    });        
});

0
投票

如果我们在组件控制器中注入Route服务,这是一个例子:

import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing'; // Because we inject service in our component
import { Router } from '@angular/router'; // Just if we need to test Route Service functionality

import { AppComponent } from './app.component';
import { DummyLoginLayoutComponent } from '../../../testing/mock.components.spec'; // Because we inject service in your component

describe('AppComponent', () => {
  let router: Router; // Just if we need to test Route Service functionality

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        DummyLoginLayoutComponent // Because we inject service in our component
      ],
      imports: [
        RouterTestingModule.withRoutes([
          { path: 'login', component: DummyLoginLayoutComponent },
        ]) // Because we inject service in our component
      ],
    }).compileComponents();

    router = TestBed.get(Router); // Just if we need to test Route Service functionality
    router.initialNavigation(); // Just if we need to test Route Service functionality
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
});

我们还可以测试其他功能,如navigate()。以防万一:

it('should call eventPage once with /register path if event is instanceof NavigationStart', fakeAsync(() => {
    spyOn(analyticService, 'eventPage');
    router.navigate(['register'])
      .then(() => {
        const baseUrl = window.location.origin;
        const url = `${baseUrl}/register`;
        expect(analyticService.eventPage).toHaveBeenCalledTimes(1);
        expect(analyticService.eventPage).toHaveBeenCalledWith(url);
      });
}));

我的文件包含所有模拟组件(mock.components.specs.ts)

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

@Component({
    selector: 'home',
    template: '<div>Dummy home component</div>',
    styleUrls: []
})

export class DummyHomeComponent { }
© www.soinside.com 2019 - 2024. All rights reserved.