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

标签 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); // ?

最佳答案

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

关于angular - 如何在 Angular 的组件测试中模拟提供的服务中的 HttpClient?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46930581/

相关文章:

javascript - 如何在 Angular4 中删除表中的行。删除按钮位于每一行

java - 使用 junit 进行多实例测试

c# - Moq dotnetcore - 无法从 'method group' 转换为 'Expression<Func<Room, bool>>'

android - 在启动所有单元测试之前调用 startKoin() 并在所有测试完成后调用 stopKoin()

javascript - 用于发布的 Angular Node 模块的版本控制

angular4 路由没有保持刷新

[innerHTML] 中的 Angular routerLink

angular - 如何在 Angular 2 Typescript 中复制到剪贴板?

unit-testing - 有没有办法对 View 中设置的 ASP.NET MVC ViewBag 属性进行单元测试?

c# - 模拟存储库返回列表