Added tests

This commit is contained in:
Giuseppe Digilio
2018-05-10 17:24:09 +02:00
parent a114650564
commit 876dba2892
8 changed files with 457 additions and 39 deletions

View File

@@ -0,0 +1,79 @@
// Load the implementations that should be tested
import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, inject, TestBed, } from '@angular/core/testing';
import 'rxjs/add/observable/of';
import { Chips } from './models/chips.model';
import { UploaderService } from '../uploader/uploader.service';
import { ChipsComponent } from './chips.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { SortablejsModule } from 'angular-sortablejs';
function createTestComponent<T>(html: string, type: { new(...args: any[]): T }): ComponentFixture<T> {
TestBed.overrideComponent(type, {
set: {template: html}
});
const fixture = TestBed.createComponent(type);
fixture.detectChanges();
return fixture as ComponentFixture<T>;
}
describe('Chips component', () => {
let testComp: TestComponent;
let testFixture: ComponentFixture<TestComponent>;
let html;
// async beforeEach
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
NgbModule.forRoot(),
SortablejsModule.forRoot({ animation: 150 }),
],
declarations: [
ChipsComponent,
TestComponent,
], // declare the test component
providers: [
ChangeDetectorRef,
ChipsComponent,
UploaderService
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
});
}));
// synchronous beforeEach
beforeEach(() => {
html = `
<ds-chips
*ngIf="chips.hasItems()"
[chips]="chips"
[editable]="true"
(selected)="onChipSelected($event)"></ds-chips>`;
testFixture = createTestComponent(html, TestComponent) as ComponentFixture<TestComponent>;
testComp = testFixture.componentInstance;
});
it('should create Chips Component', inject([ChipsComponent], (app: ChipsComponent) => {
expect(app).toBeDefined();
}));
});
// declare a test component
@Component({
selector: 'ds-test-cmp',
template: ``
})
class TestComponent {
public chips = new Chips([]);
}

View File

@@ -15,9 +15,9 @@ export const FormActionTypes = {
FORM_CHANGE: type('dspace/form/FORM_CHANGE'), FORM_CHANGE: type('dspace/form/FORM_CHANGE'),
FORM_REMOVE: type('dspace/form/FORM_REMOVE'), FORM_REMOVE: type('dspace/form/FORM_REMOVE'),
FORM_STATUS_CHANGE: type('dspace/form/FORM_STATUS_CHANGE'), FORM_STATUS_CHANGE: type('dspace/form/FORM_STATUS_CHANGE'),
FORM_ADD_ERROR: type('dspace/form/ADD_ERROR'), FORM_ADD_ERROR: type('dspace/form/FORM_ADD_ERROR'),
FORM_REMOVE_ERROR: type('dspace/form/REMOVE_ERROR'), FORM_REMOVE_ERROR: type('dspace/form/FORM_REMOVE_ERROR'),
CLEAR_ERRORS: type('dspace/form/CLEAR_ERRORS'), FORM_CLEAR_ERRORS: type('dspace/form/FORM_CLEAR_ERRORS'),
}; };
/* tslint:disable:max-classes-per-file */ /* tslint:disable:max-classes-per-file */
@@ -122,5 +122,6 @@ export class FormAddError implements Action {
*/ */
export type FormAction = FormInitAction export type FormAction = FormInitAction
| FormChangeAction | FormChangeAction
| FormRemoveAction
| FormStatusChangeAction | FormStatusChangeAction
| FormAddError | FormAddError

View File

@@ -1,40 +1,25 @@
// Load the implementations that should be tested // Load the implementations that should be tested
import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, inject, TestBed, } from '@angular/core/testing';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { import { Observable } from 'rxjs/Observable';
Component, import 'rxjs/add/observable/of';
CUSTOM_ELEMENTS_SCHEMA, import { DynamicFormControlModel, DynamicFormValidationService, DynamicInputModel } from '@ng-dynamic-forms/core';
DebugElement import { Store } from '@ngrx/store';
} from '@angular/core';
import {
async,
ComponentFixture,
inject,
TestBed,
} from '@angular/core/testing';
import { StoreModule } from '@ngrx/store';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import Spy = jasmine.Spy;
import { FormComponent } from './form.component'; import { FormComponent } from './form.component';
import { FormService } from './form.service'; import { FormService } from './form.service';
import { DynamicFormControlModel, DynamicFormValidationService, DynamicInputModel } from '@ng-dynamic-forms/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormBuilderService } from './builder/form-builder.service'; import { FormBuilderService } from './builder/form-builder.service';
import { SubmissionFormsConfigService } from '../../core/config/submission-forms-config.service'; import { FormState } from './form.reducers';
import { ResponseCacheService } from '../../core/cache/response-cache.service';
import { RequestService } from '../../core/data/request.service';
import { ObjectCacheService } from '../../core/cache/object-cache.service';
import { Observable } from 'rxjs/Observable';
function createTestComponent<T>(html: string, type: { new(...args: any[]): T }): ComponentFixture<T> { function createTestComponent<T>(html: string, type: { new(...args: any[]): T }): ComponentFixture<T> {
TestBed.overrideComponent(type, { TestBed.overrideComponent(type, {
set: { template: html } set: {template: html}
}); });
const fixture = TestBed.createComponent(type); const fixture = TestBed.createComponent(type);
@@ -110,7 +95,14 @@ describe('Form component', () => {
const formBuilderServiceStub = { const formBuilderServiceStub = {
createFormGroup: (formModel) => new FormGroup(TEST_FORM_GROUP) createFormGroup: (formModel) => new FormGroup(TEST_FORM_GROUP)
} }
const submissionFormsConfigServiceStub = { } const submissionFormsConfigServiceStub = {};
const store: Store<FormState> = jasmine.createSpyObj('store', {
/* tslint:disable:no-empty */
dispatch: {},
/* tslint:enable:no-empty */
select: Observable.of({})
});
// async beforeEach // async beforeEach
beforeEach(async(() => { beforeEach(async(() => {
@@ -121,17 +113,22 @@ describe('Form component', () => {
CommonModule, CommonModule,
FormsModule, FormsModule,
ReactiveFormsModule, ReactiveFormsModule,
StoreModule.forRoot({}),
NgbModule.forRoot(), NgbModule.forRoot(),
TranslateModule.forRoot()
], ],
declarations: [ declarations: [
FormComponent, FormComponent,
TestComponent, TestComponent,
], // declare the test component ], // declare the test component
providers: [ providers: [
ChangeDetectorRef,
DynamicFormValidationService,
FormBuilderService,
FormComponent, FormComponent,
{ provide: FormService, useValue: formServiceStub }, FormService,
{ provide: FormBuilderService, useValue: formBuilderServiceStub }, {
provide: Store, useValue: store
}
], ],
schemas: [CUSTOM_ELEMENTS_SCHEMA] schemas: [CUSTOM_ELEMENTS_SCHEMA]
}); });
@@ -141,17 +138,17 @@ describe('Form component', () => {
// synchronous beforeEach // synchronous beforeEach
beforeEach(() => { beforeEach(() => {
html = ` html = `
<ds-form #formRef="formComponent" <ds-form *ngIf="formModel" #formRef="formComponent"
[formId]="formId" [formId]="formId"
[formModel]="formModel" [formModel]="formModel"
[displaySubmit]="false"></ds-form>`; [displaySubmit]="displaySubmit"></ds-form>`;
testFixture = createTestComponent(html, TestComponent) as ComponentFixture<TestComponent>; testFixture = createTestComponent(html, TestComponent) as ComponentFixture<TestComponent>;
testComp = testFixture.componentInstance; testComp = testFixture.componentInstance;
}); });
it('should create Form Component', inject([FormComponent], (app: FormComponent) => { it('should create Form Component', inject([FormComponent], (app: FormComponent) => {
expect(app).toBeDefined(); expect(app).toBeDefined();
})); }));
@@ -166,6 +163,7 @@ class TestComponent {
public formId; public formId;
public formModel: DynamicFormControlModel[]; public formModel: DynamicFormControlModel[];
public displaySubmit = false;
constructor() { constructor() {
this.formId = 'testForm'; this.formId = 'testForm';

View File

@@ -0,0 +1,174 @@
import { formReducer } from './form.reducers';
import {
FormAddError,
FormChangeAction,
FormInitAction,
FormRemoveAction,
FormStatusChangeAction
} from './form.actions';
describe('formReducer', () => {
it('should set init state of the form', () => {
const state = {
testForm: {
data: {
'dc.contributor.author': null,
'dc.title': null,
'dc.date.issued': null,
'dc.description': null
},
valid: false,
errors: []
}
};
const formId = 'testForm';
const formData = {
'dc.contributor.author': null,
'dc.title': null,
'dc.date.issued': null,
'dc.description': null
};
const valid = false;
const action = new FormInitAction(formId, formData, valid);
const newState = formReducer({}, action);
expect(newState).toEqual(state);
});
it('should change form data on form change', () => {
const initState = {
testForm: {
data: {
'dc.contributor.author': null,
'dc.title': null,
'dc.date.issued': null,
'dc.description': null
},
valid: false,
errors: []
}
};
const state = {
testForm: {
data: {
'dc.contributor.author': null,
'dc.title': ['test'],
'dc.date.issued': null,
'dc.description': null
},
valid: false,
errors: []
}
};
const formId = 'testForm';
const formData = {
'dc.contributor.author': null,
'dc.title': ['test'],
'dc.date.issued': null,
'dc.description': null
};
const action = new FormChangeAction(formId, formData);
const newState = formReducer(initState, action);
expect(newState).toEqual(state);
});
it('should change form status on form status change', () => {
const initState = {
testForm: {
data: {
'dc.contributor.author': null,
'dc.title': ['test'],
'dc.date.issued': null,
'dc.description': null
},
valid: false,
errors: []
}
};
const state = {
testForm: {
data: {
'dc.contributor.author': null,
'dc.title': ['test'],
'dc.date.issued': null,
'dc.description': null
},
valid: true,
errors: []
}
};
const formId = 'testForm';
const action = new FormStatusChangeAction(formId, true);
const newState = formReducer(initState, action);
expect(newState).toEqual(state);
});
it('should add error to form state', () => {
const initState = {
testForm: {
data: {
'dc.contributor.author': null,
'dc.title': ['test'],
'dc.date.issued': null,
'dc.description': null
},
valid: true,
errors: []
}
};
const state = {
testForm: {
data: {
'dc.contributor.author': null,
'dc.title': ['test'],
'dc.date.issued': null,
'dc.description': null
},
valid: true,
errors: [
{
fieldId: 'dc.title',
message: 'Not valid'
}
]
}
};
const formId = 'testForm';
const fieldId = 'dc.title';
const message = 'Not valid';
const action = new FormAddError(formId, fieldId, message);
const newState = formReducer(initState, action);
expect(newState).toEqual(state);
});
it('should remove form state', () => {
const initState = {
testForm: {
data: {
'dc.contributor.author': null,
'dc.title': ['test'],
'dc.date.issued': null,
'dc.description': null
},
valid: true,
errors: []
}
};
const formId = 'testForm';
const action = new FormRemoveAction(formId);
const newState = formReducer(initState, action);
expect(newState).toEqual({});
});
});

View File

@@ -86,14 +86,16 @@ function initForm(state: FormState, action: FormInitAction): FormState {
return Object.assign({}, state, { return Object.assign({}, state, {
[ action.payload.formId ]: { [ action.payload.formId ]: {
data: action.payload.formData, data: action.payload.formData,
valid: action.payload.valid valid: action.payload.valid,
errors: []
} }
}); });
} else { } else {
const newState = Object.assign({}, state); const newState = Object.assign({}, state);
newState[ action.payload.formId ] = Object.assign({}, newState[ action.payload.formId ], { newState[ action.payload.formId ] = Object.assign({}, newState[ action.payload.formId ], {
data: action.payload.formData, data: action.payload.formData,
valid: action.payload.valid valid: action.payload.valid,
errors: []
} }
); );
return newState; return newState;

View File

@@ -0,0 +1,73 @@
import { Store, StoreModule } from '@ngrx/store';
import { async, inject, TestBed } from '@angular/core/testing';
import 'rxjs/add/observable/of';
import { FormService } from './form.service';
import { FormBuilderService } from './builder/form-builder.service';
import { AppState } from '../../app.reducer';
import { DynamicPathable } from '@ng-dynamic-forms/core/src/model/misc/dynamic-form-control-path.model';
import { DynamicFormControlModel } from '@ng-dynamic-forms/core';
import { formReducer } from './form.reducers';
describe('FormService', () => {
const formId = 'testForm';
let service: FormService;
const formData = {
'dc.contributor.author': null,
'dc.title': ['test'],
'dc.date.issued': null,
'dc.description': null
};
const formState = {
testForm: {
data: formData,
valid: true,
errors: []
}
};
const formBuilderServiceStub: any = {
getPath: (model: DynamicPathable) => [],
/* tslint:disable:no-empty */
clearAllModelsValue: (groupModel: DynamicFormControlModel[]) => {
}
/* tslint:enable:no-empty */
};
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
StoreModule.forRoot({formReducer})
],
providers: [
{provide: FormBuilderService, useValue: formBuilderServiceStub},
]
}).compileComponents();
}));
beforeEach(inject([Store], (store: Store<AppState>) => {
store
.subscribe((state) => {
state.forms = formState;
});
service = new FormService(formBuilderServiceStub, store);
}));
it('should check whether form state is init', () => {
service.isFormInitialized(formId).subscribe((init) => {
expect(init).toBe(true);
});
});
it('should return form status when isValid is called', () => {
service.isValid(formId).subscribe((status) => {
expect(status).toBe(true);
});
});
it('should return form data when getFormData is called', () => {
service.getFormData(formId).subscribe((data) => {
expect(data).toBe(formData);
});
});
});

View File

@@ -31,7 +31,7 @@ export class FormService {
/** /**
* Method to retrieve form's data from state * Method to retrieve form's data from state
*/ */
public getFormData(formId: string): Observable<FormControl> { public getFormData(formId: string): Observable<any> {
return this.store.select(formObjectFromIdSelector(formId)) return this.store.select(formObjectFromIdSelector(formId))
.filter((state) => isNotUndefined(state)) .filter((state) => isNotUndefined(state))
.map((state) => state.data) .map((state) => state.data)

View File

@@ -0,0 +1,91 @@
// Load the implementations that should be tested
import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, inject, TestBed, } from '@angular/core/testing';
import { ScrollToService } from '@nicky-lenaers/ngx-scroll-to';
import { UploaderService } from './uploader.service';
import { UploaderOptions } from './uploader-options.model';
import { UploaderComponent } from './uploader.component';
import { FileUploadModule } from 'ng2-file-upload';
import { TranslateModule } from '@ngx-translate/core';
function createTestComponent<T>(html: string, type: { new(...args: any[]): T }): ComponentFixture<T> {
TestBed.overrideComponent(type, {
set: {template: html}
});
const fixture = TestBed.createComponent(type);
fixture.detectChanges();
return fixture as ComponentFixture<T>;
}
describe('Chips component', () => {
let testComp: TestComponent;
let testFixture: ComponentFixture<TestComponent>;
let html;
// async beforeEach
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
FileUploadModule,
TranslateModule.forRoot()
],
declarations: [
UploaderComponent,
TestComponent,
], // declare the test component
providers: [
ChangeDetectorRef,
ScrollToService,
UploaderComponent,
UploaderService
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
});
}));
// synchronous beforeEach
beforeEach(() => {
html = `
<ds-uploader [onBeforeUpload]="onBeforeUpload"
[uploadFilesOptions]="uploadFilesOptions"
(onCompleteItem)="onCompleteItem($event)"></ds-uploader>`;
testFixture = createTestComponent(html, TestComponent) as ComponentFixture<TestComponent>;
testComp = testFixture.componentInstance;
});
it('should create Uploader Component', inject([UploaderComponent], (app: UploaderComponent) => {
expect(app).toBeDefined();
}));
});
// declare a test component
@Component({
selector: 'ds-test-cmp',
template: ``
})
class TestComponent {
public uploadFilesOptions: UploaderOptions = {
url: 'http://test',
authToken: null,
disableMultipart: false,
itemAlias: null
};
/* tslint:disable:no-empty */
public onBeforeUpload = () => {
};
onCompleteItem(event) {
}
/* tslint:enable:no-empty */
}