Как я могу проверить данные, поступающие с сервера, в моем тестовом файле компонента - PullRequest
0 голосов
/ 17 апреля 2020

Я пишу модульный тест для компонента, в котором я получаю список сотрудников.

У меня есть служба приложений, которая выполняет http-запрос. Служба приложений также зависит от другой службы общего назначения, которая определяет метод http get.

Я хочу проверить данные GET с помощью testObject (в файле .spe c), чтобы объект должен быть равен одному из объектов моих данных.

Я пытался смоделировать обе службы в моем файле .spe c, но я полагаю, что они реализованы неправильно, так как я я не получаю данные в моем файле .spe c.

Я немного новичок в этом, поэтому не знаю, как правильно его реализовать.

Спасибо за помощь.

.ts файл:

  ngOnInit() {
    this.getItems();
  }

  getItems() {
    this.service.getData().
    subscribe(
      response => {
        this.itemsArray = response.data;
        console.log(this.itemsArray);
      },
      error => console.log('Error: ' + error)
    );
  }

.app.service:

@Injectable()
export class AppService {

  constructor(private service: CommonCrudService) { }

    getData(): Observable<any> {
      return this.service.get('http://dummy.restapiexample.com/api/v1/employees');
    }
}

common-crud.service.ts:

@Injectable()
export class CommonCrudService {

  constructor(private http: HttpClient) { }

  private handleError(error: any) {
    console.error(error);
    return throwError(error);
  }

  public get(url: string) {
    return this.http.get(url).pipe(
    map((response: Response) => {
      return response;
    }),
    catchError((error: Response | any) => {
      console.error(error);
      return observableThrowError(error);
    }));
  }

.spe c .ts:

import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
import { CommonCrudService } from './common-crud.service';
import { Observable, of } from 'rxjs';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { mockPipe } from './app-pipe.mock';

const testObject = {
  id: '1',
  employee_name: 'Tiger Nixon',
  employee_salary: '320800',
  employee_age: '61',
  profile_image: ''
};

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        mockPipe({name: 'itemSearch'})
      ],
      imports: [
        HttpClientTestingModule
      ],
      providers: [
        {
          provide: AppService,
          useClass: MockAppService
        },
        {
          provide: CommonCrudService,
          useClass: MockCommonCrudService
        }
      ],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create the app', async(() => {
    expect(component).toBeTruthy();
  }));

});

class MockAppService {
  getData(): Observable<any> {
    return of([]);
  }
}

class MockCommonCrudService {
  get(): Observable<any> {
    return of([]);
  }
}

1 Ответ

1 голос
/ 17 апреля 2020

Вы не указали возвращаемое значение правильно. Если вы хотите установить testObject для itemsArray. Вам нужно указать возвращаемое значение функции getData () в сервисе приложения для testObject.

изменить класс MockAppService, как показано ниже.

 class MockAppService {
      getData(): Observable<any> {
        return of([testObject]);
      }
    }

тогда для проверки свойства компонента попробуйте вот так.

 it("Should test getItems()" , ()=> {
       component.getItems()
       fixture.detectChanges()
       expect(compoent.itemsArray).toEqual([testObject])
   })
...