angular - 错误:无法解析 ActivatedRoute 的所有参数:(?, ?, ?, ?, ?, ?, ?, ?)
问题描述
我正在尝试使用 Karma/Jasmine 中的 ActivatedRoute 类测试 Angular 组件,但我遇到了一个非常烦人的错误,我无法修复。Error: Can't resolve all parameters for ActivatedRoute: (?, ?, ?, ?, ?, ?, ?, ?)
我已经尝试了我在网上找到的所有解决方案,以各种方式模拟激活的路线。但我就是无法让它工作。
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute, convertToParamMap } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { SearchbarComponent } from './searchbar.component';
describe('SearchbarComponent', () => {
let component: SearchbarComponent;
let fixture: ComponentFixture<SearchbarComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ RouterTestingModule ],
declarations: [ SearchbarComponent ],
providers: [
{
provide: ActivatedRoute,
useValue: {
queryParams: of(convertToParamMap({
search: ""
}))
}
}
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(SearchbarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Input, Component, HostListener, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
...
@Component({
selector: 'searchbar',
templateUrl: './searchbar.component.html',
styleUrls: ['./searchbar.component.scss'],
providers: [ ActivatedRoute ]
})
export class SearchbarComponent implements OnInit {
constructor(private route: ActivatedRoute) {
this.route.queryParams
.subscribe(params => {
this.currentSearch = params.search;
});
}
...
}
解决方案
RouterTestingModule
处理所有与路由相关的东西的模拟,包括 ActivatedRoute。您可以删除该providers
部分,我希望它可以工作
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute, convertToParamMap } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { SearchbarComponent } from './searchbar.component';
describe('SearchbarComponent', () => {
let component: SearchbarComponent;
let fixture: ComponentFixture<SearchbarComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ RouterTestingModule ],
declarations: [ SearchbarComponent ],
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(SearchbarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
推荐阅读
- python - How to get two columns Values based on Where function in python
- ios - 返回时如何记住 ViewController 的最后一个活动?
- python - matlab 引擎没有属性“shareEngine”
- asp.net - 如何为 ASP.NET MVC 中的目录启用 CORS?
- python - Python中的双SSH隧道
- eclipse - 通过切换透视图或更改透视图来修改工作台的 Eclipse 方法是什么?
- javascript - 禁用整个部分的滚动
- mysql - 带有案例选择语句的 Sql - IN 子句
- directus - 自带数据库?
- javascript - 更改 javascript 更改功能以处理页面加载