Angular 2/4/6/7-使用路由器进行单元测试 [英] Angular 2/4/6/7 - Unit Testing with Router
本文介绍了Angular 2/4/6/7-使用路由器进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Angular 2.0.0中,我正在对使用路由器的组件进行单元测试.但是我得到提供的参数与呼叫目标的任何签名都不匹配."错误.在spec.ts中的Visual Studio代码中,新的Router()以红色
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 studio code in spec.ts it is the new Router() that is highlighted in red
如果有人能让我知道正确的语法是什么,我真的很感谢.提前致谢.我的代码如下:
I really appreciate if someone could let me know what the correct syntax would be? Thanks in advance. My code as follows:
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) {}
推荐答案
您还可以只使用RouterTestingModule并像这样监视导航功能...
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<LandingComponent>;
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']);
});
});
这篇关于Angular 2/4/6/7-使用路由器进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文