如何在Angular的组件测试中模拟提供的服务中的HttpClient?

时间:2017-10-25 10:56:10

标签: angular unit-testing

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

2 个答案:

答案 0 :(得分:6)

使用HttpClient,他们还添加了一个HttpClientTestingModule,因此您可以完全模拟服务调用... this article解释如何执行...基本上您想要 a)创建您希望返回的虚拟数据 b)创建您的服务呼叫测试 c)模拟对服务URL的调用,返回虚拟数据

答案 1 :(得分:5)

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