Как проверить карту и нажать трубку из RX JS в Angular - PullRequest
1 голос
/ 02 марта 2020

Я хочу проверить мой код ниже, но я не уверен, как проверить карту и нажать (из RX JS) функции. Должен ли я сделать шутку, использовать шпиона?

Должен ли я вообще проверять это? У меня есть привычка получать 100% покрытие только для достижения этой цели (100% покрытие), но я узнаю, что 100% не всегда нужно или полезно. Но в этом случае карта и касание довольно важны для функции. Буду очень признателен за любые советы, спасибо.

Я использую Angular 9.

Красные линии не проверены.

enter image description here

1 Ответ

1 голос
/ 02 марта 2020

Да, получение 100% покрытия, вероятно, не лучшая идея, но хорошая цель для достижения цели.

Поскольку я вижу, что ваш сервис выполняет HTTP-запросы, следуйте этому руководству для тестирования: https://medium.com/better-programming/testing-http-requests-in-angular-with-httpclienttestingmodule-3880ceac74cf.

И да, вам придется издеваться loggingService;

Как-то так:

import { TestBed } from '@angular/core/testing';
import { CoursesService } from './courses.service';
import { HttpClientTestingModule,
         HttpTestingController } from '@angular/common/http/testing';
... // the rest of your imports

describe('TemplateService', () => {
  // We declare the variables that we'll use for the Test Controller and for our Service
  let httpTestingController: HttpTestingController;
  let service: TemplateService;
  let mockLoggingService: any;

  beforeEach(() => {
    // 'loggingService' is for your own sanity and the array are all of the public methods of `loggingService`
    mockLoggingService = jasmine.createSpyObj('loggingService', ['logger']);
    TestBed.configureTestingModule({
      providers: [
                  TemplateService,
                  // every time the test asks for LoggingService, supply this mock
                  { provide: LoggingService, useValue: mockLoggingService },
     ],
      imports: [HttpClientTestingModule]
    });

    // We inject our service (which imports the HttpClient) and the Test Controller
    httpTestingController = TestBed.get(HttpTestingController);
    service = TestBed.get(TemplateService);
  });

  afterEach(() => {
    httpTestingController.verify();
  });

  // Angular default test added when you generate a service using the CLI
  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should make a get call for getTemplates and log', () => {
    const mockTemplates: Template[] = [/* you know how a template should look like so mock it*/];
   // make HTTP call take flight
    service.getTemplates().subscribe(templates => {
      expect(templates).toEqual(mockTemplates);
      expect(mockLoggingService.logger).toHaveBeenCalledWith(`User viewed templates: ${templates}`);
    });

   // have a handle on the HTTP call that is about to take flight
   const req = httpTestingController.expectOne(/* put the unique url of this method's get request that only you know of */);

   expect(req.request.method).toEqual('GET');
   // send this request for the next HTTP call
   req.flush(mockTemplates);
  });

  it('should make a get call for getTemplateById and log', () => {
    const mockTemplate: Template = {/* you know how a template should look like so mock it*/};
   // make HTTP call take flight
    service.getTemplateById(1).subscribe(template => {
      expect(template).toEqual(mockTemplate);
      expect(mockLoggingService.logger).toHaveBeenCalledWith(`User viewed template: ${template}`);
    });

   // have a handle on the HTTP call that is about to take flight
   const req = httpTestingController.expectOne(/* put the unique url of this method's get request that only you know of */);

   expect(req.request.method).toEqual('GET');
   // send this request for the next HTTP call
   req.flush(mockTemplates);
  });
});

Примечание на стороне: Ваш maps ничего не делают в обеих функциях, и они могут быть удалены. Они просто возвращают то, что получают, и ничего не трансформируют.

...