Модульное тестирование в Angular 5 с компонентами, источником данных и обслуживанием - PullRequest
0 голосов
/ 19 ноября 2018

Я как прирожденный ребенок, пишу кейсы для угловых тестов, но пытаюсь учиться, и я использую сканер Sonar для проверки покрытия кода.

Я делюсь своим кодом, пожалуйста, посмотрите:

`// test.component.ts 

dataSource: TestDataSource;
..
// method I am trying to test 

loadDataPage() {
      if (this.code === undefined || this.code === 'Test') {
        this.pageNo = this.paginator.pageIndex + 1;
        this.dataSource.loadDatas(
          this.paginator.pageIndex,
          this.paginator.pageSize,
          this.sort.active,
          this.sort.direction,
          this.input.nativeElement.value,
          this.locationSelectedValue,
          this.testticketSelectedValue,
          this.teststatusSelectedValue,
          this.styleOptionSelectedValue
        );
    } else {
      this.getUserByName(this.Name);
    }
  }

...

Ниже приведен файл источника данных:

// testDatasource.ts

export class TestDataSource implements DataSource<any> {

..
 loadDatas(pageIndex: number, pageSize: number, sortLabel: string,
        sortDirection: string, search: any, location: string[],
        testticketCount: string[], teststatus: string[], styleOption: string[]) {
        this.loadingSubject.next(true);
        this.testService.getData(pageIndex, pageSize, sortLabel,
            sortDirection, search, location,
             ticketCount, status, styleOption).pipe(catchError(() => of([])), finalize(() => this.loadingSubject.next(false)))
            .subscribe(responses => {
                this.countValue = responses['count'];
                this.dataSubject.next(responses['response']);
            });
    }

..

Ниже находится служебный файл:

//test.service.ts
export class TestService {
getData(
        pageNumber, pageSize, sortLabel, sortDirection, search,
        location, ticketCount, status, styleOption): Observable<any[]> {
        const object = {
            pageNumber: pageNumber,
            pageSize: pageSize,
            sortLabel: sortLabel,
            sortDirection: sortDirection,
            search: search,
            location: location,
            ticketCount: ticketCount,
            status: status,
            styleOption: styleOption
        };

        return this.apiService.post(this.config.api_url +
            '/testOrder/getall', object).pipe(
                map(res => res)
            );
    }

Приведенный выше файл - это мой код, который мне нужно протестировать, используя Карму и Жасмин.

То, как я пытался протестировать метод, используется совместно:

// test.component.spec.ts

it('should call and run #loaddata()', () => {
    spyOn(comp, 'loadDataPage');
    comp.testcode = 'TEST';
    comp.paginator.pageIndex = 0;
    comp.paginator.pageSize = 25;
    comp.sort.active = null;
    comp.sort.direction = 'desc';
    comp.input.nativeElement.value = null;
    comp.locationSelectedValue = [];
    comp.testticketSelectedValue = [];
    comp.teststatusSelectedValue = [];
    comp.styleOptionSelectedValue = [];

      if (!expect(comp.companycode).toEqual('TEST')) {
        expect(comp.paginator.pageIndex + 1).toBe(1);
        expect(comp.dataSource.loadDatas).toHaveBeenCalledWith(
          comp.paginator.pageIndex,
          comp.paginator.pageSize,
          comp.sort.active,
          comp.sort.direction,
          comp.input.nativeElement.value,
          comp.locationSelectedValue,
          comp.testticketSelectedValue,
          comp.teststatusSelectedValue,
          comp.styleOptionSelectedValue);
    } else {
      expect(comp.paginator.pageIndex + 1).toBe(1);
    }
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...