Как написать модульный тест для asyn c метода? - PullRequest
0 голосов
/ 03 февраля 2020

У меня есть следующий тестовый код:

import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import {inject, TestBed} from '@angular/core/testing';
import {AviorBackendService} from './avior-backend.service';

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

  it('should be created', () => {
    const service: AviorBackendService = TestBed.get(AviorBackendService);
    expect(service).toBeTruthy();
  });

  // Inject the `done` method. This will tell the test suite that asynchronous methods are being called
  // and it will mark the test as failed if within a specific timeout (usually 5s) the `done` is not called
  it('expects service to fetch data with proper sorting', (done) => {
    const service: AviorBackendService = TestBed.get(AviorBackendService);
    // tslint:disable-next-line: prefer-const
    let httpMock: HttpTestingController;
    service.getUserCollection().subscribe(data => {
      expect(data.length).toBe(7);
      const req = httpMock.expectOne('http://localhost:3000/users');
      expect(req.request.method).toEqual('GET');      // Then we set the fake data to be returned by the mock
      req.flush({firstname: 'Chad'});
      done(); // Mark the test as done
    }, done.fail); // Mark the test as failed if something goes wrong
  });
});

Мне нужно написать тест-прототип для поставляемой функции (тогда я напишу остальное для других подобных функций). Я все еще учусь писать тесты и, насколько я понимаю, мне нужно использовать макет, но я не понимаю как. Мой тестовый код:

  getUserCollection() {
    // withCredentials is very important as it passes the JWT cookie needed to authenticate
    return this.client.get<User[]>(SERVICE_URL + 'users', { withCredentials: true });
  }

Мой тестовый код выдает ошибку Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

ОБНОВЛЕНИЕ

Мой user-collection.model .ts:

import { User } from './user.model';

export interface UserCollection {

    user: User[];

}

Мой user.model.ts:

import { Role } from './role';

// was class and not interface!
export interface User {
    _id: number;
    mandator?: number;
    loginId: string;
    lastname: string;
    firstname: string;
    password: string;
    eMail: string;
    group?: string;
    role?: Role;
    active?: boolean;
    token?: string;
}

1 Ответ

2 голосов
/ 03 февраля 2020

Вы делаете flush в неправильном месте (место, которое никогда не будет пройдено).

Попробуйте следующее:

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

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

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

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

  it('expects the service to fetch data with proper sorting', () => {
    const mockReponse = { firstName: 'Chad' };

    service.getUserCollection().subscribe(data => {
      expect(data.firstName).toEqual('Chad');
    });
    const req = httpTestingController.expectOne('IN HERE PUT WHATEVER SERVICE_URL + 'users' EQUALS TO');
    expect(req.request.method).toEqual('POST');
    // send the response to the subscribe.
    req.flush(mockResponse);
  });
});

Хорошая ссылка на то, как проверить службу HTTP в Angular (https://medium.com/better-programming/testing-http-requests-in-angular-with-httpclienttestingmodule-3880ceac74cf)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...