在异步函数内部比较数据时,Angular HttpClient单元测试不会失败

时间:2019-01-21 18:06:40

标签: angular unit-testing 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刷新请求并期望数据等于数组中的第一个电话号码应该失败。

1 个答案:

答案 0 :(得分:1)

与测试有关的问题是,您使自己的“ it”函数运行并且期望异步而没有明确告诉茉莉花。

您需要使用其他函数中的done函数来告诉测试正在等待什么(在here中查看有关茉莉花异步测试的优质教程)

根据您的代码执行一个示例:

...
//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);
});
....

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