typescript 如何对使用Angle中的Router的组件进行单元测试?

sdnqo3pr  于 2022-12-19  发布在  TypeScript
关注(0)|答案(4)|浏览(126)

在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) {}
nwlls2ji

nwlls2ji1#

您也可以只使用RouterTestingModule和spyOnnavigate函数,如下所示

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); // TestBed.inject(Router) for Angular 9+

    });

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

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

jw5wzhpr2#

这是因为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,在那里你可以配置路由。

另请参阅:

unhi4e5o

unhi4e5o3#

下面是我们在组件控制器中注入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 { }
j0pj023g

j0pj023g4#

贾斯敏更适合做间谍...

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

相关问题