issues with form component tests

This commit is contained in:
lotte
2018-09-07 13:48:00 +02:00
parent 14f5c97ecc
commit 14fd58dd21
6 changed files with 348 additions and 304 deletions

View File

@@ -1,24 +1,21 @@
import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, inject, TestBed, } from '@angular/core/testing';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule, By } from '@angular/platform-browser';
import { FormControl, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import {
DynamicFormArrayModel,
DynamicFormControlEvent,
DynamicFormControlModel,
DynamicInputModel
} from '@ng-dynamic-forms/core';
import { ActionsSubject, Store } from '@ngrx/store';
import { of as observableOf } from 'rxjs';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { of as observableOf } from 'rxjs';
import { FormComponent } from './form.component';
import { FormService } from './form.service';
import { FormBuilderService } from './builder/form-builder.service';
import { FormState } from './form.reducer';
import { FormAddError, FormChangeAction, FormStatusChangeAction } from './form.actions';
import { FormAddError, FormChangeAction } from './form.actions';
import { FormFieldMetadataValueObject } from './builder/models/form-field-metadata-value.model';
import { GLOBAL_CONFIG } from '../../../config';
import { createTestComponent } from '../testing/utils';
@@ -26,7 +23,6 @@ import { getMockFormService } from '../mocks/mock-form-service';
import { getMockFormBuilderService } from '../mocks/mock-form-builder-service';
export const TEST_FORM_MODEL = [
new DynamicInputModel(
{
id: 'dc_title',
@@ -93,11 +89,12 @@ export const TEST_FORM_MODEL_WITH_ARRAY = [
})
];
fdescribe('FormComponent test suite', () => {
describe('FormComponent test suite', () => {
let testComp: TestComponent;
let formComp: FormComponent;
let testFixture: ComponentFixture<TestComponent>;
let formFixture: ComponentFixture<FormComponent>;
let dynamicForm;
const config = {
form: {
@@ -107,23 +104,10 @@ fdescribe('FormComponent test suite', () => {
}
}
} as any;
const formState: FormState = {
testForm: {
data: {
dc_title: null,
dc_title_alternative: null,
dc_publisher: null,
dc_identifier_citation: null,
dc_identifier_issn: null
},
valid: false,
errors: []
}
};
let html;
const store = new Store<FormState>(observableOf({}), new ActionsSubject(), undefined);
let formService;
let formBuilderService;
// async beforeEach
beforeEach(async(() => {
@@ -142,21 +126,19 @@ fdescribe('FormComponent test suite', () => {
], // declare the test component
providers: [
ChangeDetectorRef,
{provide: FormBuilderService, useValue: getMockFormBuilderService()},
FormComponent,
{provide: FormService, useValue: getMockFormService()},
{provide: GLOBAL_CONFIG, useValue: config},
{
provide: Store, useValue: store
}
{ provide: FormBuilderService, useValue: getMockFormBuilderService() },
{ provide: FormService, useValue: getMockFormService() },
{ provide: GLOBAL_CONFIG, useValue: config }
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
});
formService = TestBed.get(FormService);
formBuilderService = TestBed.get(FormBuilderService);
}));
describe('', () => {
// synchronous beforeEach
// // synchronous beforeEach
beforeEach(() => {
html = `
<ds-form *ngIf="formModel" #formRef="formComponent"
@@ -169,7 +151,6 @@ fdescribe('FormComponent test suite', () => {
});
it('should create FormComponent', inject([FormComponent], (app: FormComponent) => {
expect(app).toBeDefined();
}));
});
@@ -183,236 +164,246 @@ fdescribe('FormComponent test suite', () => {
formComp.formModel = TEST_FORM_MODEL;
formComp.displaySubmit = false;
formFixture.detectChanges();
spyOn(store, 'dispatch');
dynamicForm = formFixture.debugElement.query(By.css('ds-dynamic-form'));
formBuilderService.findById.and.returnValue(TEST_FORM_MODEL);
});
afterEach(() => {
formFixture.destroy();
formComp = null;
});
it('should dispatch a FormStatusChangeAction when Form group status changes', () => {
const control = formComp.formGroup.get(['dc_title']);
control.setValue('Test Title');
expect(store.dispatch).toHaveBeenCalledWith(new FormStatusChangeAction('testForm', formComp.formGroup.valid));
});
fit('should display form errors when errors are added to the state', () => {
const error = {
fieldId: 'dc_title',
fieldIndex: 0,
message: 'error.validation.required'
};
store.dispatch(new FormAddError(formComp.formId, error.fieldId, error.fieldIndex, error.message));
formFixture.detectChanges();
expect((formComp as any).formErrors[0]).toEqual(error);
});
it('should remove form errors when errors are empty in the state', () => {
(formComp as any).formErrors = [{
fieldId: 'dc_title',
message: 'error.validation.required'
}];
const errors = [];
formState.testForm.errors = errors;
store.nextState(formState);
formFixture.detectChanges();
expect((formComp as any).formErrors).toEqual(errors);
});
it('should dispatch FormChangeAction on form change', inject([FormBuilderService], (service: FormBuilderService) => {
const event = {
$event: new FormFieldMetadataValueObject('Test Title'),
context: null,
control: formComp.formGroup.get('dc_title'),
group: formComp.formGroup,
model: formComp.formModel[0],
type: 'change'
} as DynamicFormControlEvent;
spyOn(formComp.change, 'emit');
formComp.onChange(event);
expect(store.dispatch).toHaveBeenCalledWith(new FormChangeAction('testForm', service.getValueFromModel(formComp.formModel)));
expect(formComp.change.emit).toHaveBeenCalled();
}));
it('should emit change on form change', inject([FormBuilderService], (service: FormBuilderService) => {
const event = {
$event: new FormFieldMetadataValueObject('Test Title'),
context: null,
control: formComp.formGroup.get('dc_title'),
group: formComp.formGroup,
model: formComp.formModel[0],
type: 'change'
} as DynamicFormControlEvent;
spyOn(formComp.change, 'emit');
formComp.onChange(event);
expect(formComp.change.emit).toHaveBeenCalled();
}));
it('should not emit change Event on form change when emitChange is false', inject([FormBuilderService], (service: FormBuilderService) => {
const event = {
$event: new FormFieldMetadataValueObject('Test Title'),
context: null,
control: formComp.formGroup.get('dc_title'),
group: formComp.formGroup,
model: formComp.formModel[0],
type: 'change'
} as DynamicFormControlEvent;
formComp.emitChange = false;
spyOn(formComp.change, 'emit');
formComp.onChange(event);
expect(formComp.change.emit).not.toHaveBeenCalled();
}));
it('should emit blur Event on blur', () => {
const event = {
$event: new FocusEvent('blur'),
context: null,
control: formComp.formGroup.get('dc_title'),
group: formComp.formGroup,
model: formComp.formModel[0],
type: 'blur'
} as DynamicFormControlEvent;
spyOn(formComp.blur, 'emit');
formComp.onBlur(event);
expect(formComp.blur.emit).toHaveBeenCalled();
});
it('should emit focus Event on focus', () => {
const event = {
$event: new FocusEvent('focus'),
context: null,
control: formComp.formGroup.get('dc_title'),
group: formComp.formGroup,
model: formComp.formModel[0],
type: 'focus'
} as DynamicFormControlEvent;
spyOn(formComp.focus, 'emit');
formComp.onFocus(event);
expect(formComp.focus.emit).toHaveBeenCalled();
});
it('should return Observable of form status', () => {
const control = formComp.formGroup.get(['dc_title']);
control.setValue('Test Title');
formState.testForm.valid = true;
store.nextState(formState);
formFixture.detectChanges();
formComp.isValid().subscribe((valid) => {
expect(valid).toBe(true);
});
});
it('should emit submit Event on form submit whether the form is valid', () => {
const control = formComp.formGroup.get(['dc_title']);
control.setValue('Test Title');
formState.testForm.valid = true;
spyOn(formComp.submit, 'emit');
store.nextState(formState);
formFixture.detectChanges();
formComp.onSubmit();
expect(formComp.submit.emit).toHaveBeenCalled();
});
it('should not emit submit Event on form submit whether the form is not valid', () => {
spyOn((formComp as any).formService, 'validateAllFormFields');
store.nextState(formState);
formFixture.detectChanges();
formComp.onSubmit();
expect((formComp as any).formService.validateAllFormFields).toHaveBeenCalled();
});
it('should reset form group', () => {
spyOn(formComp.formGroup, 'reset');
formComp.reset();
expect(formComp.formGroup.reset).toHaveBeenCalled();
});
});
describe('', () => {
beforeEach(() => {
formFixture = TestBed.createComponent(FormComponent);
formComp = formFixture.componentInstance; // FormComponent test instance
formComp.formId = 'testFormArray';
formComp.formModel = TEST_FORM_MODEL_WITH_ARRAY;
formComp.displaySubmit = false;
formFixture.detectChanges();
spyOn(store, 'dispatch');
});
afterEach(() => {
formFixture.destroy();
formComp = null;
});
it('should return ReadOnly property from array item', inject([FormBuilderService], (service: FormBuilderService) => {
const readOnly = formComp.isItemReadOnly(formComp.formModel[0] as DynamicFormArrayModel, 0);
expect(readOnly).toBe(false);
}));
it('should dispatch FormChangeAction when an item has been added to an array', inject([FormBuilderService], (service: FormBuilderService) => {
formComp.insertItem(new Event('click'), formComp.formModel[0] as DynamicFormArrayModel, 1);
expect(store.dispatch).toHaveBeenCalledWith(new FormChangeAction('testFormArray', service.getValueFromModel(formComp.formModel)));
}));
it('should emit addArrayItem Event when an item has been added to an array', inject([FormBuilderService], (service: FormBuilderService) => {
spyOn(formComp.addArrayItem, 'emit');
formComp.insertItem(new Event('click'), formComp.formModel[0] as DynamicFormArrayModel, 1);
expect(formComp.addArrayItem.emit).toHaveBeenCalled();
}));
it('should dispatch FormChangeAction when an item has been removed from an array', inject([FormBuilderService], (service: FormBuilderService) => {
formComp.removeItem(new Event('click'), formComp.formModel[0] as DynamicFormArrayModel, 1);
expect(store.dispatch).toHaveBeenCalledWith(new FormChangeAction('testFormArray', service.getValueFromModel(formComp.formModel)));
}));
it('should emit removeArrayItem Event when an item has been removed from an array', inject([FormBuilderService], (service: FormBuilderService) => {
spyOn(formComp.removeArrayItem, 'emit');
formComp.removeItem(new Event('click'), formComp.formModel[0] as DynamicFormArrayModel, 1);
expect(formComp.removeArrayItem.emit).toHaveBeenCalled();
}));
//
// it('should dispatch a FormStatusChangeAction when Form group status changes', () => {
// // spyOn(formComp, 'onChange');
// const control = new FormControl('', Validators.required);
// const event = {
// $event: new FormFieldMetadataValueObject('Test Title'),
// context: null,
// control: control,
// group: formComp.formGroup,
// model: formComp.formModel[0],
// type: 'change'
// } as DynamicFormControlEvent;
// dynamicForm.componentInstance.change.emit(event);
//
// // expect(formComp.onChange).toHaveBeenCalledWith('testForm', formComp.formGroup.valid);
// formComp.onChange(event);
// // const control = new FormControl('', Validators.required);
// formComp.formGroup.addControl('dc_title', control);
// control.setValue('Test Title');
//
// expect(formService.changeForm).toHaveBeenCalledWith('testForm', formComp.formGroup.valid);
// });
//
// it('should display form errors when errors are added to the state', () => {
//
// const error = {formComp.formId, 'dc_title', 0, 'error.validation.required';
// formService.getFormErrors().next([error]);
// formFixture.detectChanges();
//
// expect((formComp as any).formErrors).toEqual([error]);
//
// });
//
// fit('should remove form errors when errors are empty in the state', () => {
// (formComp as any).formErrors = [{
// fieldId: 'dc_title',
// message: 'error.validation.required'
// }];
// const errors = [];
//
// formService.getFormErrors().next([]);
// formFixture.detectChanges();
//
// expect((formComp as any).formErrors).toEqual(errors);
//
// });
//
// it('should dispatch FormChangeAction on form change', inject([FormBuilderService], (service: FormBuilderService) => {
// const event = {
// $event: new FormFieldMetadataValueObject('Test Title'),
// context: null,
// control: formComp.formGroup.get('dc_title'),
// group: formComp.formGroup,
// model: formComp.formModel[0],
// type: 'change'
// } as DynamicFormControlEvent;
//
// spyOn(formComp.change, 'emit');
//
// formComp.onChange(event);
//
// expect(store.dispatch).toHaveBeenCalledWith(new FormChangeAction('testForm', service.getValueFromModel(formComp.formModel)));
// expect(formComp.change.emit).toHaveBeenCalled();
// }));
//
// it('should emit change on form change', inject([FormBuilderService], (service: FormBuilderService) => {
// const event = {
// $event: new FormFieldMetadataValueObject('Test Title'),
// context: null,
// control: formComp.formGroup.get('dc_title'),
// group: formComp.formGroup,
// model: formComp.formModel[0],
// type: 'change'
// } as DynamicFormControlEvent;
//
// spyOn(formComp.change, 'emit');
//
// formComp.onChange(event);
//
// expect(formComp.change.emit).toHaveBeenCalled();
// }));
//
// it('should not emit change Event on form change when emitChange is false', inject([FormBuilderService], (service: FormBuilderService) => {
// const event = {
// $event: new FormFieldMetadataValueObject('Test Title'),
// context: null,
// control: formComp.formGroup.get('dc_title'),
// group: formComp.formGroup,
// model: formComp.formModel[0],
// type: 'change'
// } as DynamicFormControlEvent;
//
// formComp.emitChange = false;
// spyOn(formComp.change, 'emit');
//
// formComp.onChange(event);
//
// expect(formComp.change.emit).not.toHaveBeenCalled();
// }));
//
// it('should emit blur Event on blur', () => {
// const event = {
// $event: new FocusEvent('blur'),
// context: null,
// control: formComp.formGroup.get('dc_title'),
// group: formComp.formGroup,
// model: formComp.formModel[0],
// type: 'blur'
// } as DynamicFormControlEvent;
//
// spyOn(formComp.blur, 'emit');
//
// formComp.onBlur(event);
//
// expect(formComp.blur.emit).toHaveBeenCalled();
// });
//
// it('should emit focus Event on focus', () => {
// const event = {
// $event: new FocusEvent('focus'),
// context: null,
// control: formComp.formGroup.get('dc_title'),
// group: formComp.formGroup,
// model: formComp.formModel[0],
// type: 'focus'
// } as DynamicFormControlEvent;
//
// spyOn(formComp.focus, 'emit');
//
// formComp.onFocus(event);
//
// expect(formComp.focus.emit).toHaveBeenCalled();
// });
//
// it('should return Observable of form status', () => {
//
// const control = formComp.formGroup.get(['dc_title']);
// control.setValue('Test Title');
// formState.testForm.valid = true;
// store.nextState(formState);
// formFixture.detectChanges();
//
// formComp.isValid().subscribe((valid) => {
// expect(valid).toBe(true);
// });
// });
//
// it('should emit submit Event on form submit whether the form is valid', () => {
//
// const control = formComp.formGroup.get(['dc_title']);
// control.setValue('Test Title');
// formState.testForm.valid = true;
// spyOn(formComp.submit, 'emit');
//
// store.nextState(formState);
// formFixture.detectChanges();
//
// formComp.onSubmit();
// expect(formComp.submit.emit).toHaveBeenCalled();
// });
//
// it('should not emit submit Event on form submit whether the form is not valid', () => {
//
// spyOn((formComp as any).formService, 'validateAllFormFields');
//
// store.nextState(formState);
// formFixture.detectChanges();
//
// formComp.onSubmit();
// expect((formComp as any).formService.validateAllFormFields).toHaveBeenCalled();
// });
//
// it('should reset form group', () => {
//
// spyOn(formComp.formGroup, 'reset');
//
// formComp.reset();
//
// expect(formComp.formGroup.reset).toHaveBeenCalled();
// });
// });
//
// describe('', () => {
// beforeEach(() => {
//
// formFixture = TestBed.createComponent(FormComponent);
// formComp = formFixture.componentInstance; // FormComponent test instance
// formComp.formId = 'testFormArray';
// formComp.formModel = TEST_FORM_MODEL_WITH_ARRAY;
// formComp.displaySubmit = false;
// formFixture.detectChanges();
// spyOn(store, 'dispatch');
// });
//
// afterEach(() => {
// formFixture.destroy();
// formComp = null;
// });
//
// it('should return ReadOnly property from array item', inject([FormBuilderService], (service: FormBuilderService) => {
// const readOnly = formComp.isItemReadOnly(formComp.formModel[0] as DynamicFormArrayModel, 0);
//
// expect(readOnly).toBe(false);
// }));
//
// it('should dispatch FormChangeAction when an item has been added to an array', inject([FormBuilderService], (service: FormBuilderService) => {
// formComp.insertItem(new Event('click'), formComp.formModel[0] as DynamicFormArrayModel, 1);
//
// expect(store.dispatch).toHaveBeenCalledWith(new FormChangeAction('testFormArray', service.getValueFromModel(formComp.formModel)));
// }));
//
// it('should emit addArrayItem Event when an item has been added to an array', inject([FormBuilderService], (service: FormBuilderService) => {
// spyOn(formComp.addArrayItem, 'emit');
//
// formComp.insertItem(new Event('click'), formComp.formModel[0] as DynamicFormArrayModel, 1);
//
// expect(formComp.addArrayItem.emit).toHaveBeenCalled();
// }));
//
// it('should dispatch FormChangeAction when an item has been removed from an array', inject([FormBuilderService], (service: FormBuilderService) => {
// formComp.removeItem(new Event('click'), formComp.formModel[0] as DynamicFormArrayModel, 1);
//
// expect(store.dispatch).toHaveBeenCalledWith(new FormChangeAction('testFormArray', service.getValueFromModel(formComp.formModel)));
// }));
//
// it('should emit removeArrayItem Event when an item has been removed from an array', inject([FormBuilderService], (service: FormBuilderService) => {
// spyOn(formComp.removeArrayItem, 'emit');
//
// formComp.removeItem(new Event('click'), formComp.formModel[0] as DynamicFormArrayModel, 1);
//
// expect(formComp.removeArrayItem.emit).toHaveBeenCalled();
// }));
})
});

View File

@@ -1,6 +1,13 @@
import {distinctUntilChanged, map, filter} from 'rxjs/operators';
import { ChangeDetectorRef, Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core';
import { distinctUntilChanged, filter, map } from 'rxjs/operators';
import {
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnDestroy,
OnInit,
Output
} from '@angular/core';
import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms';
import {
@@ -10,22 +17,11 @@ import {
DynamicFormGroupModel,
DynamicFormLayout,
} from '@ng-dynamic-forms/core';
import { select, Store } from '@ngrx/store';
import { findIndex } from 'lodash';
import { AppState } from '../../app.reducer';
import {
FormChangeAction,
FormInitAction,
FormRemoveAction,
FormRemoveErrorAction,
FormStatusChangeAction
} from './form.actions';
import { FormBuilderService } from './builder/form-builder.service';
import { Observable , Subscription } from 'rxjs';
import { Observable, Subscription } from 'rxjs';
import { hasValue, isNotEmpty, isNotNull, isNull } from '../empty.util';
import { FormService } from './form.service';
import { formObjectFromIdSelector } from './selectors';
import { FormEntry, FormError } from './form.reducer';
/**
@@ -92,8 +88,7 @@ export class FormComponent implements OnDestroy, OnInit {
constructor(private formService: FormService,
protected changeDetectorRef: ChangeDetectorRef,
private formBuilderService: FormBuilderService,
private store: Store<AppState>) {
private formBuilderService: FormBuilderService) {
}
/**
@@ -132,13 +127,14 @@ export class FormComponent implements OnDestroy, OnInit {
ngOnInit() {
if (!this.formGroup) {
this.formGroup = this.formBuilderService.createFormGroup(this.formModel);
} else {
this.formModel.forEach((model) => {
this.formBuilderService.addFormGroupControl(this.formGroup, this.parentFormModel, model);
});
}
this.store.dispatch(new FormInitAction(this.formId, this.formBuilderService.getValueFromModel(this.formModel), this.getFormGroupValidStatus()));
this.formService.initForm(this.formId, this.formModel, this.getFormGroupValidStatus());
// TODO: take a look to the following method:
// this.keepSync();
@@ -148,46 +144,61 @@ export class FormComponent implements OnDestroy, OnInit {
this.subs.push(this.formGroup.statusChanges.pipe(
filter((currentStatus) => this.formValid !== this.getFormGroupValidStatus()))
.subscribe((currentStatus) => {
// Dispatch a FormStatusChangeAction if the form status has changed
this.store.dispatch(new FormStatusChangeAction(this.formId, this.getFormGroupValidStatus()));
this.formService.setStatusChanged(this.formId, this.getFormGroupValidStatus());
this.formValid = this.getFormGroupValidStatus();
}));
this.subs.push(
this.store.pipe(
select(formObjectFromIdSelector(this.formId)),
this.formService.getForm(this.formId).pipe(
filter((formState: FormEntry) => !!formState && (isNotEmpty(formState.errors) || isNotEmpty(this.formErrors))),
map((formState) => formState.errors),
distinctUntilChanged(),)
// .delay(100) // this terrible delay is here to prevent the detection change error
distinctUntilChanged())
// .delay(100) // this terrible delay is here to prevent the detection change error
.subscribe((errors: FormError[]) => {
const {formGroup, formModel} = this;
const { formGroup, formModel } = this;
errors
.filter((error: FormError) => findIndex(this.formErrors, {fieldId: error.fieldId, fieldIndex: error.fieldIndex}) === -1)
.filter((error: FormError) => findIndex(this.formErrors, {
fieldId: error.fieldId,
fieldIndex: error.fieldIndex
}) === -1)
.forEach((error: FormError) => {
const {fieldId} = error;
const {fieldIndex} = error;
const { fieldId } = error;
const { fieldIndex } = error;
let field: AbstractControl;
if (!!this.parentFormModel) {
field = this.formBuilderService.getFormControlById(fieldId, formGroup.parent as FormGroup, formModel, fieldIndex);
} else {
field = this.formBuilderService.getFormControlById(fieldId, formGroup, formModel, fieldIndex);
}
console.log('1', error);
if (field) {
console.log('2',error);
const model: DynamicFormControlModel = this.formBuilderService.findById(fieldId, formModel);
console.log('4',error);
this.formService.addErrorToField(field, model, error.message);
// this.formService.validateAllFormFields(formGroup);
console.log('5',error);
this.changeDetectorRef.detectChanges();
}
console.log('4',error);
});
console.log(errors);
this.formErrors
.filter((error: FormError) => findIndex(errors, {fieldId: error.fieldId, fieldIndex: error.fieldIndex}) === -1)
.filter((error: FormError) => findIndex(errors, {
fieldId: error.fieldId,
fieldIndex: error.fieldIndex
}) === -1)
.forEach((error: FormError) => {
const {fieldId} = error;
const {fieldIndex} = error;
const { fieldId } = error;
const { fieldIndex } = error;
let field: AbstractControl;
if (!!this.parentFormModel) {
field = this.formBuilderService.getFormControlById(fieldId, formGroup.parent as FormGroup, formModel, fieldIndex);
@@ -200,7 +211,7 @@ export class FormComponent implements OnDestroy, OnInit {
this.formService.removeErrorFromField(field, model, error.message);
}
});
console.log(this.formErrors);
this.formErrors = errors;
this.changeDetectorRef.detectChanges();
})
@@ -214,7 +225,7 @@ export class FormComponent implements OnDestroy, OnInit {
this.subs
.filter((sub) => hasValue(sub))
.forEach((sub) => sub.unsubscribe());
this.store.dispatch(new FormRemoveAction(this.formId));
this.formService.removeForm(this.formId)
}
/**
@@ -245,9 +256,8 @@ export class FormComponent implements OnDestroy, OnInit {
}
onChange(event: DynamicFormControlEvent): void {
const action: FormChangeAction = new FormChangeAction(this.formId, this.formBuilderService.getValueFromModel(this.formModel));
this.store.dispatch(action);
this.formService.changeForm(this.formId, this.formModel);
this.formGroup.markAsPristine();
if (this.emitChange) {
@@ -257,7 +267,7 @@ export class FormComponent implements OnDestroy, OnInit {
const control: FormControl = event.control;
const fieldIndex: number = (event.context && event.context.index) ? event.context.index : 0;
if (control.valid) {
this.store.dispatch(new FormRemoveErrorAction(this.formId, event.model.id, fieldIndex));
this.formService.removeError(this.formId, event.model.id, fieldIndex);
}
}
@@ -290,14 +300,14 @@ export class FormComponent implements OnDestroy, OnInit {
const formArrayControl = this.formGroup.get(this.formBuilderService.getPath(arrayContext)) as FormArray;
this.removeArrayItem.emit(this.getEvent($event, arrayContext, index, 'remove'));
this.formBuilderService.removeFormArrayGroup(index, formArrayControl, arrayContext);
this.store.dispatch(new FormChangeAction(this.formId, this.formBuilderService.getValueFromModel(this.formModel)));
this.formService.changeForm(this.formId, this.formModel);
}
insertItem($event, arrayContext: DynamicFormArrayModel, index: number): void {
const formArrayControl = this.formGroup.get(this.formBuilderService.getPath(arrayContext)) as FormArray;
this.formBuilderService.insertFormArrayGroup(index, formArrayControl, arrayContext);
this.addArrayItem.emit(this.getEvent($event, arrayContext, index, 'add'));
this.store.dispatch(new FormChangeAction(this.formId, this.formBuilderService.getValueFromModel(this.formModel)));
this.formService.changeForm(this.formId, this.formModel);
}
protected getEvent($event: any, arrayContext: DynamicFormArrayModel, index: number, type: string): DynamicFormControlEvent {
@@ -314,6 +324,6 @@ export class FormComponent implements OnDestroy, OnInit {
}
const model = context.group[0] as DynamicFormControlModel;
const control = group.controls[index] as FormControl;
return {$event, context, control, group, model, type};
return { $event, context, control, group, model, type };
}
}

View File

@@ -10,8 +10,14 @@ import { FormBuilderService } from './builder/form-builder.service';
import { DynamicFormControlModel } from '@ng-dynamic-forms/core';
import { isEmpty, isNotUndefined } from '../empty.util';
import { uniqueId } from 'lodash';
import { FormChangeAction } from './form.actions';
import {
FormChangeAction,
FormInitAction,
FormRemoveAction, FormRemoveErrorAction,
FormStatusChangeAction
} from './form.actions';
import { GLOBAL_CONFIG, GlobalConfig } from '../../../config';
import { FormEntry } from './form.reducer';
@Injectable()
export class FormService {
@@ -142,4 +148,28 @@ export class FormService {
}
return (this.config.form.validatorMap.hasOwnProperty(validator)) ? this.config.form.validatorMap[validator] : validator;
}
public initForm(formId: string, model: DynamicFormControlModel[], valid: boolean) {
this.store.dispatch(new FormInitAction(formId, this.formBuilderService.getValueFromModel(model), valid))
}
public setStatusChanged(formId: string, valid: boolean) {
this.store.dispatch(new FormStatusChangeAction(formId, valid))
}
public getForm(formId: string): Observable<FormEntry> {
return this.store.pipe(select(formObjectFromIdSelector(formId)));
}
public removeForm(formId: string) {
this.store.dispatch(new FormRemoveAction(formId));
}
public changeForm(formId: string, model: DynamicFormControlModel[]) {
this.store.dispatch(new FormChangeAction(formId, this.formBuilderService.getValueFromModel(model)));
}
public removeError(formId: string, eventModelId: string, fieldIndex: number) {
this.store.dispatch(new FormRemoveErrorAction(formId, eventModelId, fieldIndex));
}
}

View File

@@ -1,12 +1,23 @@
import { FormService } from '../form/form.service';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';
import { map } from 'rxjs/operators';
export function getMockFormService(
id$: string = 'random_id'
id$: string = 'random_id',
errors = new BehaviorSubject([])
): FormService {
return jasmine.createSpyObj('FormService', {
getUniqueId: id$,
resetForm: {},
validateAllFormFields: {}
validateAllFormFields: {},
getForm: errors.pipe(map((err) => { return {data: {}, valid: true, errors: err} })),
removeForm: undefined,
removeError: undefined,
changeForm: undefined,
setStatusChanged: undefined,
initForm: undefined,
getFormErrors: errors,
addErrorToField: undefined
});
}

View File

@@ -1,7 +1,6 @@
import {map} from 'rxjs/operators';
import { map } from 'rxjs/operators';
import { Action } from '@ngrx/store';
import { Observable , BehaviorSubject } from 'rxjs';
import { BehaviorSubject, Observable } from 'rxjs';
export class MockStore<T> extends BehaviorSubject<T> {

View File

@@ -49,7 +49,10 @@ export function createTranslateLoader() {
AppModule
],
providers: [
{ provide: Angulartics2GoogleAnalytics, useClass: AngularticsMock },
{
provide: Angulartics2GoogleAnalytics,
useClass: AngularticsMock
},
{
provide: AuthService,
useClass: ServerAuthService