我有一个使用 Angular 18 的应用程序,并且有一个使用服务的组件。该服务调用 HttpClient,获取实体列表,组件在构造函数上使用该列表。
服务的单元测试与provideHttpClient和provideHttpClientTest一起正常工作。但是,由于 HttpClient 注入失败,该组件失败了
Chrome 126.0.0.0 (Windows 10) CardListComponent 应该创建 FAILED NullInjectorError:R3InjectorError(独立[CardListComponent])[HttpClient - > HttpClient - > HttpClient]: NullInjectorError:没有 HttpClient 的提供者! 错误属性:Object({ ngTempTokenPath: null, ngTokenPath: [ 'HttpClient', 'HttpClient', 'HttpClient' ] })
下面是单元测试的代码。我尝试了这里找到的许多不同的方法,甚至官方文档中的方法,但似乎都不起作用。
describe('CardListComponent', () => {
let component: CardListComponent;
let fixture: ComponentFixture<CardListComponent>;
let cardService: CardServiceService;
const cardServiceMock: jasmine.SpyObj<CardServiceService> = jasmine.createSpyObj('CardServiceService', ['getAllCards']);
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CardListComponent],
providers: [
provideHttpClient,
provideHttpClientTesting,
CardListComponent,
{
provide: CardServiceService,
useValue: cardServiceMock,
},
],
}).compileComponents();
fixture = TestBed.createComponent(CardListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
provideHttpClient
和 provideHttpClientTesting
是您需要调用的函数。
providers: [
provideHttpClient(),
provideHttpClientTesting(),
],