首页 > 解决方案 > 如何在 Jest Angular 中为 GroupBy 函数编写测试用例

问题描述

我有以下代码:

groupBy<T, K>(list: T[], getKey: (item: T) => K) {
    const map = new Map<K, T[]>();
    list.forEach((item) => {
      const key = getKey(item);
      const collection = map.get(key);
      if (!collection) {
        map.set(key, [item]);
      } else {
        collection.push(item);
      }
    });
    return Array.from(map.values());
  }


const groupedById = this.groupBy(alertLog, (alrts: AlertLog) => alrts.AlertGroupID);
    groupedById.forEach((value) => {
      const groupID = value[0].AlertGroupID;
      const groupedBySeverity = this.groupBy(value, (item) => item.Severity);
      groupedBySeverity.forEach((byServ) => {
        const groupedByName = this.groupBy(byServ, (item) => item.Name);
        groupedBySeverity.forEach(value => {
          if (groupID === 'System') {
            const severity = byServ[0].Severity;
            this.donutData[TABS.SYSTEM][severity] = groupedByName.length;
          } else if (groupID === 'CUSTOM') {
            const severity = byServ[0].Severity;
            this.donutData[TABS.CUSTOM][severity] = groupedByName.length;
          } else if (groupID === 'UCM') {
            const severity = byServ[0].Severity;
            this.donutData[TABS.VOICE_VIDEO][severity] = groupedByName.length;
          } else if (groupID === 'IM&P') {
            const severity = byServ[0].Severity;
            this.donutData[TABS.IMnP][severity] = groupedByName.length;
          } else if (groupID === 'CUC') {
            const severity = byServ[0].Severity;
            this.donutData[TABS.UnityConnection][severity] = groupedByName.length;
          }
        });
      });
    });

现在,我想为这个函数写一个 UT。我该如何进行?

我的spec文件现在看起来像这样:

import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing';
import { DataService } from '../../../services/data.service';
import { FeatureService } from '../../utility/feature.service';
import { RouterTestingModule } from '@angular/router/testing';
import { TimeAgoPipe } from '../../pipe/time-ago.pipe';
import { SystemComponent } from './system.component';
import { createComponent, Page, provideMockObject } from '@webex/common/test-utils';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import {  ReplaySubject } from 'rxjs';
import { OverviewMetrics } from '../interfaces/overview-metrics';

const MockDataService = {
  wsData$ : new ReplaySubject<OverviewMetrics>(1)
}

class SystemComponentPage extends Page<SystemComponent> {
  constructor(fixture: ComponentFixture<SystemComponent>) {
    super(fixture);
  }
  get getDonutComponent() {
    return this.elementQueryAll('webex-chartjs-donut-chart');
  }

  get getTabList() {
    return this.elementQueryAll('md-tab-list');
  }
}


describe('SystemComponent', () => {
  let component: SystemComponent;
  let fixture: ComponentFixture<SystemComponent>;
  let page: SystemComponentPage;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [ SystemComponent, TimeAgoPipe ],
      providers: [
        provideMockObject(DataService),
        provideMockObject(FeatureService),
        {
          provide: DataService,
          useValue: MockDataService
        }
      ],
      imports: [
        RouterTestingModule
      ],
      schemas: [
        CUSTOM_ELEMENTS_SCHEMA
      ]
    })
    .compileComponents();
  }));

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

  const initComponent = () => {
    ({ fixture, component, page } = createComponent(
      SystemComponent,
      SystemComponentPage
    ));
    fixture.detectChanges();
  };

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

  it('should contain donut card', () => {
    expect(page.getDonutComponent).toBeTruthy();
  });

  // it('should call ngAfterViewInit', () => {
  //   component.ngAfterViewInit();
  //   setTimeout(()=>{
  //     expect(component.setupSubscribers).toHaveBeenCalled();
  //    },100)
  // });

  it('should contain TabList', () => {
    expect(page.getTabList).toBeTruthy();
  })

  it('should call tabChanged function', () => {
    component.tabChanged('System');
    setTimeout(()=>{
      expect(component.activeTab).toBe('System');
     },100)

      // const tabChanged = jest.fn();
  });
});

标签: angular

解决方案


推荐阅读