尝试在角度中模拟测试用例的服务,但仍然"No Provider for HTTPClient"



我正试图在我的主组件中为Angular中的一个项目运行测试用例。该组件使用了一个ApiCallService,我正试图为测试模拟它。然而,我不断地抛出同样的错误。"create"测试用例运行,但查看页面上是否写入了"test"的测试用例会出现"No Provider for HTTPClient"错误。HttpClient和HttpClientModule也在app.module.ts中导入。

import { HttpClient, HttpClientModule } from '@angular/common/http';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HomeComponent } from './home.component';
import { ApiCallService } from 'src/app/core/service/api-call.service';

describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
let service: ApiCallService;
let httpMock: HttpTestingController;
let httpClient: HttpClient;



beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [ApiCallService, HomeComponent]
});
service = TestBed.inject(ApiCallService);
httpMock = TestBed.get(HttpTestingController);
httpClient = TestBed.inject(HttpClient);
});

it('should create', () => {
expect(ApiCallService).toBeTruthy();
});
});



it('TEST123', () => {
const fixture = TestBed.createComponent(HomeComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('p')?.textContent).toContain('Test');
});

如果您正在单元测试HomeComponent,那么您做得不对。你应该做的是:

  • 从TestBed的"providers"中删除HomeComponent,并将其添加到"declarations"下
  • 如果HomeComponent没有直接使用(在构造函数中注入(HttpClient服务,则不需要使用HttpClientTestingModule,相反,您必须创建一个间谍来模拟ApiCallService,如Angular文档中所述
  • 如果HomeComponent直接使用HttpClient服务,则必须测试HTTP请求。这是文件。你还得嘲笑ApiCallService

相关内容

  • 没有找到相关文章

最新更新