【问题标题】:How to mock HttpClient in a provided service in a component test in Angular?如何在 Angular 的组件测试中模拟提供的服务中的 HttpClient?
【发布时间】:2017-10-25 10:56:09
【问题描述】:

假设我有一个使用 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); // ?

【问题讨论】:

  • 考虑到这是单元测试,正确的做法是模拟整个服务。

标签: angular unit-testing


【解决方案1】:

要模拟 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);
    });
  });
});

【讨论】:

    【解决方案2】:

    这是我在测试HttpClient时遵循的方法

    1. 创建模拟 HttpClient 对象

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

      providers: [{ provide: HttpClient, useValue: httpClientSpy }]
      
    3. 返回beforeEach()it() 内的虚拟值

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

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

    【讨论】:

      猜你喜欢
      • 2016-12-15
      • 2020-04-19
      • 2017-12-10
      • 2017-02-15
      • 2018-09-28
      • 2020-11-19
      • 2021-09-18
      • 2015-07-07
      • 2019-11-23
      相关资源
      最近更新 更多