Угловая ошибка кармы / жасмина: невозможно прочитать свойство 'frmUser' из неопределенного - PullRequest
0 голосов
/ 11 июня 2018

Я новичок в модульном тестировании и пытаюсь протестировать базовую форму в приложении.Это просто форма, где пользователь регистрируется и отправляет некоторые учетные данные.Я пытаюсь протестировать валидаторы, но у меня проблемы с запуском юнит-теста.Я получаю эту ошибку при предварительном формировании теста:

TypeError: Cannot read property 'frmUser' of undefined
TypeError: Cannot read property 'frmUser' of undefined
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/components/user/user.component.spec.ts:54:29)
    at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:388:1)
    at ProxyZoneSpec.webpackJsonp../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:288:1)
    at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:387:1)
    at Zone.webpackJsonp../node_modules/zone.js/dist/zone.js.Zone.run (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:138:1)
    at runInTestZone (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:509:1)
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:524:1)
    at attempt (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?73bc53d3671677e6a093fc74e4f9bcde57e5f7ad:4289:46)
    at ZoneQueueRunner.QueueRunner.run (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?73bc53d3671677e6a093fc74e4f9bcde57e5f7ad:4217:20)
    at runNext (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?73bc53d3671677e6a093fc74e4f9bcde57e5f7a

Вот мой класс компонентов, где я делаю свою форму:

  frmUser: FormGroup;
  userInfo: User;
  userId: number;
  fileType: any[] = ["Claim", "Policy"];
  programs: any;
  constructor(public dialog: MatDialog, public dialogRef: MatDialogRef<UserComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private fb: FormBuilder, private httpService: HttpService, private httpClient: HttpClient) {
    this.userId = this.data.userId;

  }

  ngOnInit() {
    console.log(this.fileType);
    this.getPrograms();
    this.createUserForm();
    if (this.userId > 0)
      this.loadUser();
  }

И вот где я создаю поля ввода:

createUserForm() {
    this.frmUser = this.fb.group(
      {
        UserID: [],
        FirstName: ["", [Validators.required, Validators.maxLength(50)]],
        MiddleName: [],
        LastName: ["", [Validators.required, Validators.maxLength(50)]],
        EmailAddress: [{ value: '', disabled: this.userId > 0 }, [Validators.required, Validators.email]],
        UserAccessDetail: this.fb.array([this.createUserProgram()])
      }
    )
  }

Мой тестовый класс:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, FormsModule, FormControl, FormBuilder, FormArray, FormGroup, Validators } from '@angular/forms';
import { UserComponent } from './user.component';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material/dialog';

import { MatDialogModule} from '@angular/material';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { HttpService } from '../../services/http.service';
import { HttpClient } from '@angular/common/http';
import { inject } from '@angular/core/testing';
import { User } from '../../models/user';


fdescribe("Form User", () => {
let component: UserComponent;
let fixture: ComponentFixture<UserComponent>;
beforeEach(async(() => {



  TestBed.configureTestingModule({
    declarations: [
      UserComponent
    ],

    imports: [FormsModule,ReactiveFormsModule],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ],

    providers: [
      { provide: MatDialog, useValue: {} },
      { provide: MatDialogRef, useValue: {} },
      { provide:  MAT_DIALOG_DATA, useValue: {} },
      { provide:  HttpService, useValue: {} },
      { provide:  HttpClient, useValue: {} },


  ]

  }).compileComponents();

beforeEach(() => {

  fixture = TestBed.createComponent(UserComponent);
  component = fixture.componentInstance;

  component.ngOnInit();
})

}));

it('Should prompt an invalid textbox validator', () => {



  let textField = component.frmUser.get('FirstName');

  textField.setValue('');

  expect(textField.valid).toBeFalsy();
})

})

Спасибо!

1 Ответ

0 голосов
/ 25 сентября 2018
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, FormsModule, FormControl, FormBuilder, FormArray, FormGroup, Validators } from '@angular/forms';
import { UserComponent } from './user.component';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material/dialog';

import { MatDialogModule} from '@angular/material';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { HttpService } from '../../services/http.service';
import { HttpClient } from '@angular/common/http';
import { inject } from '@angular/core/testing';
import { User } from '../../models/user';


fdescribe("Form User", () => {
let component: UserComponent;
let fixture: ComponentFixture<UserComponent>;
beforeEach(async(() => {



  TestBed.configureTestingModule({
    declarations: [
      UserComponent
    ],

    imports: [FormsModule,ReactiveFormsModule],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ],

    providers: [
      { provide: MatDialog, useValue: {} },
      { provide: MatDialogRef, useValue: {} },
      { provide:  MAT_DIALOG_DATA, useValue: {} },
      { provide:  HttpService, useValue: {} },
      { provide:  HttpClient, useValue: {} },


  ]

  }).compileComponents();

  fixture = TestBed.createComponent(UserComponent);
  component = fixture.componentInstance;

  component.ngOnInit();

}));

it('Should prompt an invalid textbox validator', () => {



  let textField = component.frmUser.get('FirstName');

  textField.setValue('');

  expect(textField.valid).toBeFalsy();
})

})
...