当 FormGroup 设置为禁用时如何使用 Jasmine 进行单元测试?

How to unit test with Jasmine when FormGroup is set to disabled?

我有一个 angular 8 应用程序,我正在使用 Jasmine Karma 进行单元测试。我想测试一个在 NgOninit 函数中被禁用的 Formbuilder:

我是这样的:component.ts

constructor(
    private dossierService: DossierService,
    private route: ActivatedRoute,
    private sanitizer: DomSanitizer,
    private dossierFileService: DossierFileService,
    private errorProcessor: ErrorProcessor,
    private dialog: MatDialog
  ) {
    this.dossierItems = this.route.snapshot.data.dossierItems;
    this.editDossierForm = this.formBuilder.group({});
    this.editDossierForm.disable();
 
    this.dossier = this.route.snapshot.data.dossier;
    this.dossierItems = route.snapshot.data.dossierItems;
    this.profileImagefile = this.route.snapshot.data.profileImage;
 
    this.editDossierForm = this.formBuilder.group({
      firstName: this.formBuilder.control(this.dossier.firstName, [Validators.required, Validators.maxLength(255)]),
      lastName: this.formBuilder.control(this.dossier.lastName, [Validators.required, Validators.maxLength(255)]),
      mobile: this.formBuilder.control(this.dossier.mobile, [Validators.maxLength(255)]),
      company: this.formBuilder.control(this.dossier.company, [Validators.maxLength(255)]),
      buddy: this.formBuilder.control(this.dossier.buddy, [Validators.maxLength(255)]),
      supervisor: this.formBuilder.control(this.dossier.supervisor, [Validators.maxLength(255)]),
      dateOfBirth: this.formBuilder.control(this.dossier.dateOfBirth)
    });
  }
  ngOnInit(): void {
    this.editDossierForm.disable();
  }
}

这是它的规格文件:


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

  beforeEach(async(() => {


    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, DossierModule, BrowserModule],
      declarations: [DossierPersonalDataComponent],
      providers: [
          DossierFileService,
          ErrorProcessor,
          {
            provide: ActivatedRoute,
            useValue: {
              snapshot: {
                data: {
                  dossier: {
                    firstName: 'hello',
                    lastName: 'world',
                    mobile: '111-111-1111',
                    company: 'carapax',
                    buddy: 'bud',
                    supervisor: 'super',
                    dateOfBirth: '1900-01-01',
                  },
                  dossierItems: [], // mock
                  profileImage: '',
                }
              }
            }
          },
        {
          // DossierFileService, These have to be outside of the braces
          // ErrorProcessor,

          provide: DomSanitizer,
          useValue: {
            sanitize: () => 'safeString',
            bypassSecurityTrustHtml: () => 'safeString'
          }
        }
      ]
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(DossierPersonalDataComponent);
        component = fixture.componentInstance;
      });
  }));


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

但在即时报道中,它保持红色:

  }
  ngOnInit(): void {
    this.editDossierForm.disable();
  }

那么如何覆盖这部分呢?

谢谢

好的,

如果我这样做:

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

我收到这个错误:

DossierPersonalDataComponent > should create
TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.

在我的测试中,我看到了这个:

 get profileImageUrl() {
    return this.profileImagefile === null
      ? '/assets/placeholder.jpg'
      : this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(this.profileImagefile));
  }

和这一行:

 ? '/assets/placeholder.jpg'

是黄色的。分支未涵盖。

您需要执行一个fixture.detectChanges()。第一次调用会触发ngOnInit。之后它只会触发变化检测。

因此,根据您的测试,您可以在 beforeEach 块中包含一个 fixture.detectChanges()

如果您不想为每个测试用例 ngOnInit 内部发生的事情监视或设置不同的模拟,我只会推荐这种方法。

我通常在声明间谍后在每个测试用例中添加它。所以你的测试看起来应该是这样的:

it('should create', () => {
    // spy on anything you would like. e.g the disable call of your form
   
    // then trigger onInit
    fixture.detectChanges();

    // then run your expectations
    expect(component).toBeTruthy();
  });