如何编写方法的单元测试用例[Angular]

时间:2020-03-19 05:50:14

标签: angular typescript unit-testing karma-jasmine angular-test

我是Angular的初学者。我正在努力学习Typescript,现在被告知要用Jasmine和Karma为我创建的每个componentservice编写单元测试用例。我看过许多教程来学习 Angular中的单元测试。我是一名实习生,昨天我提出了一个Pull请求,我的技术负责人对此发表了以下评论。

enter image description here

这是我编写的代码。

filter-bar.component.ts

import { Component, OnInit, ViewChild, OnDestroy, Input, ChangeDetectorRef } from '@angular/core';
import './filter-bar.component.scss';
import { SisenseService } from '../services/sinsense.service';
import { SisenseConfigService } from '../services/sinsense-config.service';
import { Dashboard, Widget } from 'src/app/shared/models/sisenseConfig';
...

@Component({
    selector: 'app-filter-bar',
    templateUrl: './filter-bar.component.html'
})
export class FilterBarComponent implements OnInit, OnDestroy {
  selectedMembersCount: number;
  dataUnavailable: boolean;

  constructor(
    public sisenseService: SisenseService,
    public sisenseConfigService: SisenseConfigService
  ) {}

  ngOnInit() {
    this.getDataFromWidget();
  }

  getDataFromWidget() {
    this.sisenseService.getWidgetData(
    this.sisenseConfigService.getDashboardId(Dashboard.POPULATION),
    this.sisenseConfigService.getWidgetInfo(Dashboard.POPULATION, Widget.UNIQUE_LIVES).id,
      widgetData => {
        this.selectedMembersCount = widgetData.queryResult.value.data;
        this.changeDetector.detectChanges();
      },
      () => {
        this.dataUnavailable = true;
      }
    );
  }
}

这是我编写的规范文件:

filter-bar.component.spec.ts

import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FilterBarComponent } from './filter-bar.component';
import { SisenseFilterService } from '../services/sinsense-filter.service';
import { PopUpService } from '@wuitk6/angular/components/popup/popup.service';
import { SisenseService } from '../services/sinsense.service';
import { SisenseConfigService } from '../services/sinsense-config.service';

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

    mockSisenseConfigService.getWidgetInfo.and.returnValue({ id: 'demo_ID' });

        fixture = TestBed.createComponent(FilterBarComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });
});

这是服务,(我不知道是谁编写了这段代码):

sisense-config.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/do';
...
import { ErrorService } from './error.service';

// This is to avoid compile errors in typescript.
// The real variable will be added when sisense.js is loaded
declare var Sisense: any;

@Injectable({
    providedIn: 'root'
})
export class SisenseConfigService {
  constructor(private http: HttpClient, private errorService: ErrorService) {}

  getDashboardId(dashboardName: string): string {
    ...
  }

  getWidgetInfo(dashboardName: string, widgetName: string): ISisenseWidget {
   ...
   return widgetInfo;
  }
}

我已经写了测试文件,但她对此并不满意。请帮助我,我的技术主管到底要什么。随时询问更多代码详细信息。

1 个答案:

答案 0 :(得分:1)

这对您有帮助


describe('FilterPanelComponent', () => {
    let component: FilterBarComponent;
    let fixture: ComponentFixture<FilterBarComponent>;
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [
                FilterBarComponent
            ],
            imports: [],
            providers: [
                {
                    provide: SisenseService,
                    useClass: SisenseServiceStub
                },
                SisenseConfigService
            ]
        }).compileComponents();
    }));

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

    it('should call getDataFromWidget() on init method',()=>{
        spyOn(component,'getDataFromWidget').and.callThrough();
        component.ngOnInit();
        expect(component.getDataFromWidget).toHaveBeenCalled()
    })

    it('getDataFromWidget should set selected member count',()=>{
        component.selectedMembersCount = 0;
        component.getDataFromWidget();
        expect(component.selectedMembersCount).toEqual(1);
        fixture.detectChanges();
        const htmlEle  = fixture.debugElement.nativeElement.querySelector('#some-count'); // For class try query(By.css('.some-count')).nativeElement;
        expect(htmlEle.innerHTML).toBe(1);        
    })
});

// this is the stub she is talking about
export class SisenseServiceStub{
    getWidgetData(){
        return of({
            queryResult : {
                value : {
                    data : 1
                }
            }
        })
    }
}

几个月前,我还看到我的一些大三学生在单元测试中苦苦挣扎。因此,我写了series of articles which can help you as well

尝试一下,让我知道是否有帮助。 Here is how you play with stubs and spies