[我正在尝试测试使用功能getCurrentNavigation()
从导航获取数据的组件,当我将其与ng serve
一起使用时,该组件运行正常,没有任何错误,但是我的测试是在说:
Component2Component>应该创建TypeError:this.router.getCurrentNavigation不是函数
这是我的组件为获取数据所做的事情:
constructor(public router: Router) {
if (
this.router.getCurrentNavigation() &&
this.router.getCurrentNavigation().extras
) {
console.log(this.router.getCurrentNavigation().extras);
}
这是我的测试:
describe('Component2Component', () => {
let component: Component2Component;
let fixture: ComponentFixture<Component2Component>;
const routerSpy = jasmine.createSpyObj('Router', ['navigate']);
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [Component2Component],
imports: [CommonModule, RouterTestingModule],
providers: [{ provide: Router, useValue: routerSpy }]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Component2Component);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
为什么我的测试无法识别此功能?
您在配置测试模块时提供的routerSpy
不具有功能getCurrentNavigation
。它包含的唯一功能是navigate
,因为这是通过jasmine.createSpyObj
创建它时定义的。
jasmine.createSpyObj
可以通过以下一行更改上面的行来解决问题。
const routerSpy = jasmine.createSpyObj('Router', ['navigate']);
让const routerSpy = jasmine.createSpyObj('Router', ['getCurrentNavigation', 'navigate']);
做他的工作
RouterTestingModule
设置要用于测试的路由器,并提供开箱即用的间谍实现。但是,您通过提供自己的RouterTestingModule
覆盖了此内容。因此,您应该摆脱RouterTestingModule
并按以下方式配置测试模块。
routerSpy
如果您需要在测试功能中的某处访问routerSpy
,只需从TestBed.configureTestingModule({
declarations: [Component2Component],
imports: [CommonModule, RouterTestingModule]
}).compileComponents();
中检索它,如下所示。
Router