簡體   English   中英

如何在 Angular 的組件測試中模擬提供的服務中的 HttpClient?

[英]How to mock HttpClient in a provided service in a component test in Angular?

假設我有一個使用 HttpClient 的服務,

@Injectable()
export class MyService {
  constructor(protected httpClient: HttpClient) { .. }
}

然后是使用此服務的組件。

@Component({
  selector: 'my-component'
})

export class SendSmsComponent {
  constructor(private MyService) { .. }
}

如何在模擬 HttpClient 而不是整個服務時測試這個組件?

TestBed.configureTestingModule({
  declarations: [MyComponent],
  providers: [
    { provide: MyService, useClass: MyService } // ?
  ]
}).compileComponents();

httpMock = TestBed.get(HttpTestingController); // ?

要模擬 HttpClient,您可以將HttpClientTestingModuleHttpTestingController一起使用

完成相同操作的示例代碼

import { TestBed, ComponentFixture } from '@angular/core/testing';
import { Type } from '@angular/core';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { SendSmsComponent } from './send-sms/send-sms.component';
import { ApiService } from '@services/api.service';

describe('SendSmsComponent ', () => {
  let fixture: ComponentFixture<SendSmsComponent>;
  let app: SendSmsComponent;
  let httpMock: HttpTestingController;

  describe('SendSmsComponent ', () => {
    beforeEach(async () => {
      TestBed.configureTestingModule({
        imports: [
          HttpClientTestingModule,
        ],
        declarations: [
          SendSmsComponent,
        ],
        providers: [
          ApiService,
        ],
      });

      await TestBed.compileComponents();

      fixture = TestBed.createComponent(SendSmsComponent);
      app = fixture.componentInstance;
      httpMock = fixture.debugElement.injector.get<HttpTestingController>(HttpTestingController as Type<HttpTestingController>);

      fixture.detectChanges();
    });

    afterEach(() => {
      httpMock.verify();
    });

    it('test your http call', () => {
      const dummyUsers = [
        { name: 'John' },
      ];

      app.getUsers();
      const req = httpMock.expectOne(`${url}/users`);
      req.flush(dummyUsers);

      expect(req.request.method).toBe('GET');
      expect(app.users).toEqual(dummyUsers);
    });
  });
});

這是我在測試HttpClient時遵循的方法

  1. 創建模擬HttpClient對象

    const httpClientSpy = jasmine.createSpyObj('HttpClient', ['post', 'get']);
  2. providers中注入模擬對象

    providers: [{ provide: HttpClient, useValue: httpClientSpy }]
  3. beforeEach()it()中返回虛擬值

    httpClientSpy.post.and.returnValue(of({ status: 200, data: {} })); httpClientSpy.get.and.returnValue(of({ status: 200, data: {} }));
  4. 示例測試用例

    it('should return data for abc endpoint', () => { service.methodWithHttpRequest().subscribe(data => expect(data.status).toBe(200)); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM