gpt4 book ai didi

angular - 错误 : Can't resolve all parameters for ActivatedRoute: (? , ?, ?, ?, ?, ?, ?, ?)

转载 作者:行者123 更新时间:2023-12-05 01:58:36 26 4
gpt4 key购买 nike

我正在尝试使用 Karma/Jasmine 中的 ActivatedRoute 类测试 Angular 组件,但我遇到了一个非常烦人的错误,我无法修复。 错误:无法解析 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();
});
});

关于angular - 错误 : Can't resolve all parameters for ActivatedRoute: (? , ?, ?, ?, ?, ?, ?, ?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68501142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com