首页 > 解决方案 > 比较异步函数内部的数据时,Angular HttpClient 单元测试不会失败

问题描述

我正在尝试对一些简单的 GET 请求进行单元测试,无论我做什么,我都不能让测试失败。

如果我将其更改('GET')('POST')它将失败,但无论如何所有的 api 数据都会通过。

import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';

import { mockPhoneNumbers } from '../mocks/data/phoneNumbers.mock';
import { PhoneNumberApiService } from './phone-number-api.service';

describe('PhoneNumberApiService', () => {
  let service: PhoneNumberApiService;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [PhoneNumberApiService],
    });

    service = TestBed.get(PhoneNumberApiService);
    httpTestingController = TestBed.get(HttpTestingController);
  });

  afterEach(() => {
    // After every test, assert that there are no more pending requests.
    httpTestingController.verify();
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should get the phone numbers successfully', () => {
    service
      .getPhoneNumbers()
      .subscribe(phoneNumbers => {
        expect(phoneNumbers).toEqual('bob');
        expect(phoneNumbers[0].id).toEqual('b8bfea4d-a26f-9e4e-cbd4-39eb69cdaa58');
        expect(phoneNumbers[1].friendlyName).toEqual('Dev Test');
      });

    const req = httpTestingController.expectOne('phoneNumbers');

    expect(req.request.method).toEqual('GET');

    req.flush(mockPhoneNumbers);
  });

  it('should get the phone number details successfully', () => {
    const { id: phoneNumberId } = mockPhoneNumbers[0];

    service
      .getPhoneNumberDetails(phoneNumberId)
      .subscribe(phoneNumber => expect(phoneNumber).toEqual(mockPhoneNumbers[0]));

    const req = httpTestingController.expectOne(`phoneNumbers/${phoneNumberId}`);

    expect(req.request.method).toEqual('GET');

    req.flush('bob');
  });
});

当然用模拟数据刷新请求然后期望模拟数据bob是错误的。在底部测试中,刷新请求bob并期望数据等于数组中的第一个电话号码应该会失败。

标签: angularunit-testingangular-httpclient

解决方案


关于你的测试的问题是你让你的“它”功能和期望异步没有明确告诉茉莉。

您需要在 other 中使用 done 函数来告诉测试等待某些东西(在这里查看关于 jasmine 异步测试的好教程)

遵循基于您的代码的示例:

...
//Receive the done function like this
it('should get the phone numbers successfully', (done) => {
    service
      .getPhoneNumbers()
      .subscribe(phoneNumbers => {
        expect(phoneNumbers).toEqual('bob');
        expect(phoneNumbers[0].id).toEqual('b8bfea4d-a26f-9e4e-cbd4-39eb69cdaa58');
        expect(phoneNumbers[1].friendlyName).toEqual('Dev Test');
        //Tell the test that only in here all the work was done
        done();
      });
    const req = httpTestingController.expectOne('phoneNumbers');

    expect(req.request.method).toEqual('GET');

    req.flush(mockPhoneNumbers);
});
....

此外,为了回答您的猜测,jest 是一个测试运行程序,并且构建在 jasmine 框架之上(这意味着 jest 语法类似于 jasmin,但不相等)。但是对于这种情况,我想使用 done 将解决您的问题。


推荐阅读