我如何对 returns Promise 的异步方法进行单元测试

How do I Unit Test an Async method that returns a Promise

我正在尝试使用 returns 在我的 Angular 应用程序中承诺的方法测试服务。

但我一直收到错误消息异步函数未在 5000 毫秒内完成

我的服务是这样的

  public async startApp(data) {
    if (data === { }) this.logout()
    const url = environment.API_HOST + environment.ENDPOINT + '/start-app'
    return this.sendRequest<responseType>(url, data).toPromise()
  }

  private sendRequest<T>(url: string, data: any): Observable<T> {
    return this.http.post<T>(
      url, data, { headers: this.headers(), observe: 'response', responseType: 'json' }
    ).pipe(
      map((resp: any) => {
        return resp.body
      }))
  }

我的规范文件如下所示:

describe('MyService', () => {
      let service: MyService

      TestBed.configureTestingModule({ providers: [ MyService ] })

      service = TestBed.get(MyService)
    })

    it('should start app', async (done: DoneFn) => {
       const res = await service.startApp({ data: 'someData' })
       done()
    })

我做错了什么?

如果可能的话,我会避免监视 sendRequest,因为它是一个私有方法,否则我无法测试它

看到你的应用正在做http,你需要在你的配置中注入它。

import { HttpClientTestingModule,
         HttpTestingController } from '@angular/common/http/testing';
......
describe('MyService', () => {
  let httpTestingController: HttpTestingController;
  let service: MyService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [MyService],
      imports: [HttpClientTestingModule],
    });
    // get a handle on the HTTPController
    httpTestingController = TestBed.get(HttpTestingController);
    service = TestBed.get(CoursesService);
  });

  afterEach(() => {
    // verify no pending requests after each test
    httpTestingController.verify();
  });

  it('should start app and send a post request', async (done: DoneFn) => {
       service.startApp({ data: 'someData' }).then(response => {
         expect(response.body).toBe('helloWorld');
         // put the rest of your assertions here.
         done();
       });
       const mockResponse = { body: 'helloWorld' }; // mock the response to what you would like
       const req = httpTestingController.expectOne(... put here whatever the url, data is/ will resolve to);
       expect(req.request.method).toEqual('POST');
       // for the next HTTP request for that URL, give this as the response
       req.flush(mockResponse);
  });
});

startApp 调用一个函数,该函数以可观察的方式进行 API 调用,但您将其转换为承诺,但我很确定我为您提供的内容应该很好.

很好 link 适合你:https://medium.com/better-programming/testing-http-requests-in-angular-with-httpclienttestingmodule-3880ceac74cf