Тестирование Angular компонента с использованием JEST - PullRequest
1 голос
/ 25 апреля 2020

Я недавно начал использовать JEST с Angular, и мне не удалось найти четкий пример, поэтому хочу поделиться здесь, чтобы он мог быть полезен для других.

У меня есть следующий AppComponent.ts :

import { Component, OnInit } from '@angular/core';
import { ApiService } from './services/api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  public title = 'jestTest';
  public jsonData = [];

  constructor(private apiService: ApiService) { }

  ngOnInit() {
    this.apiService.getData().subscribe((data: []) => {
      if (data) {
        this.jsonData = data;
      } else {
        this.jsonData = [];
      }
    });
  }

}

Внедрить простую службу http для извлечения некоторых записей из базы данных и имеет переменную «title». В компоненте init я выполняю вызов и получаю результаты.

В моем HTML я просто отображаю тест:

<div> 
  <span>{{ title }}</span>
  <router-outlet></router-outlet>
</div>

Вот значение c .ts file: AppComponent.spe c .ts:

import { render } from '@testing-library/angular';
import { AppComponent } from './app.component';
import { async, TestBed, ComponentFixture, inject } from '@angular/core/testing';
import { AppRoutingModule } from './app-routing.module';
import { APP_BASE_HREF } from '@angular/common';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ApiService } from './services/api.service';
import { of } from 'rxjs';

const dataArray = [
  {
    object1: 'Object one'
  },
  {
    object2: 'Object two'
  },
  {
    object3: 'Object three'
  }
];

const mockAPIService = {
  getData: jest.fn()
};

describe('AppComponent', () => {
  let component: AppComponent;
  let service: ApiService;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [
        AppRoutingModule,
        HttpClientTestingModule
      ],
      providers: [
        { provide: APP_BASE_HREF, useValue: '/' },
        { provide: ApiService, useValue: mockAPIService },
      ]
    })
      .compileComponents();
  }));

  afterEach(() => {
    if (fixture) {
      fixture.destroy();
    }
    mockAPIService.getData.mockReset();
  });

  it('should render the component', async () => {
    mockAPIService.getData.mockImplementationOnce(() => of(dataArray));
    const { getByText } = await render(AppComponent);
    expect(getByText('jestTest'));
  });

  it('Service injected via inject(...) and TestBed.get(...) should be the same instance',
    inject([ApiService], (injectService: ApiService) => {
      service = TestBed.get(ApiService);
      expect(injectService).toBe(service);
    })
  );

  it('should return a list if data available', async () => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    mockAPIService.getData.mockImplementationOnce(() => of(dataArray));
    component.ngOnInit();
    expect(component.jsonData.length).toBeGreaterThanOrEqual(1);
  });

  it('should return a empty list if no data available', async () => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    mockAPIService.getData.mockImplementationOnce(() => of(null));
    component.ngOnInit();
    expect(component.jsonData.length).toEqual(0);
  });

});

Покрытие кода указывает, что строка 14 не покрыта. т.е. конструктор (частный apiService: ApiService) {}

------------------------|---------|----------|---------|---------|-------------------
File                    | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------------------|---------|----------|---------|---------|-------------------
All files               |     100 |       80 |     100 |     100 |                  
 app                    |     100 |    83.33 |     100 |     100 |                  
  app.component.html    |     100 |      100 |     100 |     100 |                  
  app.component.ts      |     100 |    83.33 |     100 |     100 | 14            

Почему это не охватывается?

Было бы замечательно, если бы его можно было проверить, чтобы другие могли также ссылаться на него модульное тестирование.

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