typescript 成角单元测试:如何在函数中传递FormGroupDirective?

x6yk4ghg  于 2023-03-24  发布在  TypeScript
关注(0)|答案(1)|浏览(131)

我正在尝试单元测试一个函数,该函数采用FormGroupDirective类型的参数。我能够测试所有逻辑,但无法理解应该采用什么参数来调用resetForm()函数。下面是我正在测试的代码。

<form [formGroup]="logForm" #formDirective="ngForm" (submit)="onSave(formDirective)">...</form>
onSave(formDirective: FormGroupDirective) {
  this._http.save(this.logForm.value).subscribe({
    next: response => {
      this._notification.show({ message: response.message, action: 'SUCCESS', panelClass: 'success' });
      formDirective.resetForm();
      this.logForm.reset();
      this.trailerHeading = 'Trailer';
      this.showAllTrailers = false;
      this.trailerList = [];
    }
  });
}

在单元测试时,我在调用onSave(...)方法时传递了null作为值。这在执行formDirective.resetForm()时正确地抛出了错误。
我写的测试用例是:

import { HttpClientTestingModule } from "@angular/common/http/testing";
import { CUSTOM_ELEMENTS_SCHEMA } from "@angular/core";
import { ComponentFixture, TestBed, waitForAsync } from "@angular/core/testing";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { RouterTestingModule } from "@angular/router/testing";
import { HttpClientService } from "@service/http-client.service";
import { of } from "rxjs";
import { MaterialModule } from "src/app/material/material.module";
import { TrailerLogComponent } from "./trailer-log.component";

describe('TrailerLogComponent', () => {

    let component: TrailerLogComponent, fixture: ComponentFixture<TrailerLogComponent>,
        _httpService: HttpClientService;

    beforeEach(waitForAsync(() => {
        TestBed.configureTestingModule({
            imports: [MaterialModule, RouterTestingModule, FormsModule, ReactiveFormsModule, HttpClientTestingModule, BrowserAnimationsModule],
            declarations: [TrailerLogComponent],
            providers: [HttpClientService],
            schemas: [CUSTOM_ELEMENTS_SCHEMA],
            teardown: { destroyAfterEach: false }
        }).compileComponents();
        _httpService = TestBed.inject(HttpClientService);
        fixture = TestBed.createComponent(TrailerLogComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    }));

    it('should save the trailer log form', () => {
        const response: { message: string } = { message: '' };
        spyOn(_httpService, 'save').and.returnValue(of(response));
        component.onSave(null); // what should I pass here??
        fixture.detectChanges();
        expect(component.trailerHeading).toEqual('Trailer');
        expect(component.showAllTrailers).toBeFalsy();
        expect(component.trailerList.length).toEqual(0);
    });
});

component.onSave(null)被调用时抛出错误,因为我传递null。
我应该在这里传递什么而不是NULL来使它正常工作?

ar7v8xwq

ar7v8xwq1#

您可以尝试创建指令的示例

component.onSave(new FormGroupDirective());

或者只是具有模拟函数属性的对象

component.onSave({
 resetForm: () => void 0
});

相关问题