blob: 571419491313578cf865d204df86802b6ad86639 [file] [log] [blame]
/*
******************************************************************************
* Copyright © 2018 PTA GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*
******************************************************************************
*/
import { async, fakeAsync, ComponentFixture, TestBed, tick } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { SimpleChange } from '@angular/core';
import { MockComponent } from '../../testing/mock.component';
import { StringToDatePipe } from '../../common-components/pipes/string-to-date.pipe';
import { SessionContext } from '../../common/session-context';
import { DocumentService } from './../../services/document.service';
import { AbstractMockObservableService } from '../../testing/abstract-mock-observable.service';
import { RoleAccessHelperService } from '../../services/jobs/role-access-helper.service';
import { GridMeasureDetailTabComponent } from './grid-measure-detail-tab.component';
import { USERS } from '../../test-data/users';
import { DOCUMENTS } from './../../test-data/documents';
import { GRIDMEASURE } from '../../test-data/grid-measures';
import { RoleAccess } from '../../model/role-access';
import { Globals } from '../../common/globals';
import { Document } from '../../model/document';
import { GridMeasure } from '../../model/grid-measure';
import * as FileSaver from 'file-saver';
import { GridMeasureService } from '../../services/grid-measure.service';
import { BACKENDSETTINGS } from '../../test-data/backend-settings';
import { ToasterMessageService } from '../../services/toaster-message.service';
import { MessageService } from 'primeng/api';
describe('GridMeasureDetailTabComponent', () => {
let component: GridMeasureDetailTabComponent;
let fixture: ComponentFixture<GridMeasureDetailTabComponent>;
let sessionContext: SessionContext;
let toasterMessageService: ToasterMessageService;
let gridmeasures: GridMeasure[];
let messageService: MessageService;
let mockGridMeasureService;
let mockDocService: MockDocumentService;
let roleAccessHelper: RoleAccessHelperService;
class MockDocumentService extends AbstractMockObservableService {
public uploadGridMeasureAttachments(gridmeasuereId: number, file: File) {
return this;
}
public getGridMeasureAttachments(gridmeasuereId: number) {
return this;
}
public deleteGridMeasureAttachment(documentId: number, index: number) {
return this;
}
public downloadGridMeasureAttachment(documentId: number) {
return this;
}
}
class MockGridMeasureService extends AbstractMockObservableService {
getAffectedResourcesDistinct() {
return this;
}
}
let originalTimeout;
beforeEach(async(() => {
messageService = new MessageService;
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;
gridmeasures = JSON.parse(JSON.stringify(GRIDMEASURE));
sessionContext = new SessionContext();
mockDocService = new MockDocumentService();
mockGridMeasureService = new MockGridMeasureService();
roleAccessHelper = new RoleAccessHelperService();
toasterMessageService = new ToasterMessageService(sessionContext, messageService);
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [
GridMeasureDetailTabComponent,
StringToDatePipe,
MockComponent({ selector: 'input', inputs: ['options'] }),
MockComponent({ selector: 'app-loading-spinner', inputs: [] })
],
providers: [
SessionContext,
{ provide: DocumentService, useValue: mockDocService },
{ provide: GridMeasureService, useValue: mockGridMeasureService },
{ provide: RoleAccessHelperService, useValue: roleAccessHelper },
{ provide: ToasterMessageService, useValue: toasterMessageService }
]
})
.compileComponents();
}));
beforeEach(async(() => {
sessionContext.setCurrUser(USERS[0]);
sessionContext.setAllUsers(USERS);
// we need to init the component and the path... because of OnInit
mockDocService.content = [{ id: 1, documentName: 'docdoc.doc' }];
const roleAcess: RoleAccess = {
editRoles: [{
name: 'planned-policies-measureplanner',
gridMeasureStatusIds: [
0,
1
]
}, {
name: 'planned-policies-superuser',
gridMeasureStatusIds: [
0,
1
]
}, {
name: 'planned-policies-measureapplicant',
gridMeasureStatusIds: [
0,
1
]
}],
controls: [{
gridMeasureStatusId: 0,
activeButtons: [
'save',
'apply',
'cancel'
],
inactiveFields: [
'titeldermassnahme'
]
},
{
gridMeasureStatusId: 1,
activeButtons: [
'save',
'cancel',
'forapproval'
],
inactiveFields: [
'titeldermassnahme'
]
}],
stornoSection:
{
'stornoRoles': [
'planned-policies-measureapplicant',
'planned-policies-measureplanner',
'planned-policies-measureapprover',
'planned-policies-requester',
'planned-policies-clearance'
]
},
duplicateSection:
{
'duplicateRoles': [
'planned-policies-measureapplicant'
]
}
};
roleAccessHelper.init(roleAcess);
mockGridMeasureService.content = JSON.parse(JSON.stringify(GRIDMEASURE));
sessionContext.setBackendsettings(JSON.parse(JSON.stringify(BACKENDSETTINGS)));
fixture = TestBed.createComponent(GridMeasureDetailTabComponent);
component = fixture.componentInstance;
}));
afterEach(async(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
}));
it('should create', () => {
expect(component).toBeTruthy();
});
it('should be in able to give an input value < 1000 in the field appointmentNumberOf', async(() => {
component.gridMeasureDetail.appointmentNumberOf = 999;
spyOn(component, 'checkAppointmentNumberOfValue').and.callThrough();
component.checkAppointmentNumberOfValue(component.gridMeasureDetail.appointmentNumberOf);
fixture.whenRenderingDone().then(() => {
fixture.detectChanges();
expect(component.checkAppointmentNumberOfValue).toHaveBeenCalled();
expect(component.isAppointmentNumberOfValid).toBeTruthy();
});
}));
it('should react if input value > 999 in the field appointmentNumberOf', async(() => {
fixture.detectChanges();
component.gridMeasureDetail.appointmentNumberOf = 1000;
spyOn(component, 'checkAppointmentNumberOfValue').and.callThrough();
component.checkAppointmentNumberOfValue(component.gridMeasureDetail.appointmentNumberOf);
fixture.whenRenderingDone().then(() => {
fixture.detectChanges();
expect(component.checkAppointmentNumberOfValue).toHaveBeenCalled();
expect(component.isAppointmentNumberOfValid).toBeFalsy();
expect(component.gridMeasureDetail.appointmentNumberOf).toBe(0);
});
}));
it('should set form to readonly', () => {
component.readOnlyForm = false;
fixture.detectChanges();
component.ngOnChanges({
readOnlyForm: new SimpleChange(component.readOnlyForm, true, true)
});
fixture.detectChanges();
expect(component.isValidForSave).toBeTruthy();
});
it('should set current date correctly', () => {
const datevalue = new Date().toISOString();
console.log(datevalue.substr(0, 16));
expect(datevalue.substr(0, 16)).toBe(component.getCurrentDateTime().substr(0, 16));
});
it('should enable save button after filling required field', () => {
spyOn(component, 'onGridMeasureTitleChange').and.callThrough();
const newVal = 'TitleTest';
component.gridMeasureDetail.title = newVal;
// Todo call the change Event over dispatcher for Example not the method itself
component.onGridMeasureTitleChange(newVal);
fixture.detectChanges();
fixture.whenRenderingDone().then(() => {
fixture.detectChanges();
expect(component.isValidForSave).toBeTruthy('enabled for saving');
expect(component.onGridMeasureTitleChange).toHaveBeenCalled();
});
});
it('should disable save button after cleaning required field', () => {
spyOn(component, 'onGridMeasureTitleChange').and.callThrough();
const newVal = '';
component.gridMeasureDetail.title = newVal;
// Todo call the change Event over dispatcher for Example not the method itself
component.onGridMeasureTitleChange(newVal);
fixture.detectChanges();
fixture.whenRenderingDone().then(() => {
fixture.detectChanges();
expect((component as any).validForSave).toBeFalsy();
expect(component.onGridMeasureTitleChange).toHaveBeenCalled();
});
});
it('should result in invalid form after change on plannedEndtimeGridmeasure field', () => {
spyOn(component, 'onGridMeasureTitleChange').and.callThrough();
const newVal = 'TitleTest';
component.gridMeasureDetail.title = newVal;
component.gridMeasureDetail.plannedEndtimeGridmeasure = '2016-01-16T11:11:00z';
// Todo call the change Event over dispatcher for Example not the method itself
component.onGridMeasureTitleChange(newVal);
fixture.detectChanges();
fixture.whenRenderingDone().then(() => {
fixture.detectChanges();
expect((component as any).validForm).toBeFalsy();
expect(component.onGridMeasureTitleChange).toHaveBeenCalled();
});
});
////////// UPLOAD DOCUMENT ////////////////
it('should delete attached document', async(() => {
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.gridMeasureDetail.statusId = Globals.STATUS.NEW;
component.readOnlyForm = false;
spyOn(component, 'deleteDocument').and.callThrough();
component.listOfDocuments = DOCUMENTS;
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
const button = fixture.debugElement.nativeElement.querySelector('span.remove');
button.click();
fixture.detectChanges();
expect(component.deleteDocument).toHaveBeenCalled();
});
}));
it('should handleFileInput correctly', async(() => {
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.gridMeasureDetail.statusId = Globals.STATUS.APPLIED;
component.readOnlyForm = false;
// specs compliant (as of March 2018 only Chrome)
// Firefox < 62 workaround exploiting https://bugzilla.mozilla.org/show_bug.cgi?id=1422655
const fileList = new ClipboardEvent('').clipboardData || new DataTransfer();
const fileMock = new File(['foo'], 'programmatically_created.pdf', { type: 'application/pdf' });
fileList.items.add(fileMock);
component.handleFileInput(fileList.files);
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.fileSelected).toBeTruthy();
});
}));
xit('should show a message and fail on handleFileInput: file already exists and status is applied', async(() => {
fixture.detectChanges();
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.gridMeasureDetail.statusId = Globals.STATUS.APPLIED;
component.readOnlyForm = false;
// TODO fill it via getDocumentsForId
component.listOfDocumentsNames.push(DOCUMENTS[1].documentName);
fixture.detectChanges();
spyOn(toasterMessageService, 'showWarn').and.callThrough();
// specs compliant (as of March 2018 only Chrome)
// Firefox < 62 workaround exploiting https://bugzilla.mozilla.org/show_bug.cgi?id=1422655
const fileList = new ClipboardEvent('').clipboardData || new DataTransfer();
const fileMock = new File(['foo'], 'test6.txt', { type: 'application/pdf' });
fileList.items.add(fileMock);
component.handleFileInput(fileList.files);
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.fileSelected).toBeFalsy();
expect(toasterMessageService.showWarn).toHaveBeenCalled();
});
}));
it('should show a message: multiple files selected', async(() => {
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.gridMeasureDetail.statusId = Globals.STATUS.APPLIED;
component.readOnlyForm = false;
spyOn(toasterMessageService, 'showWarn').and.callThrough();
// specs compliant (as of March 2018 only Chrome)
// Firefox < 62 workaround exploiting https://bugzilla.mozilla.org/show_bug.cgi?id=1422655
const fileList = new ClipboardEvent('').clipboardData || new DataTransfer();
const fileMock = new File(['foo'], 'programmatically_created.pdf', { type: 'application/pdf' });
const fileMock2 = new File(['foo'], 'programmatically_created2.pdf', { type: 'application/pdf' });
fileList.items.add(fileMock);
fileList.items.add(fileMock2);
component.handleFileInput(fileList.files);
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.fileSelected).toBeTruthy();
expect(toasterMessageService.showWarn).toHaveBeenCalled();
});
}));
it('should fail on handleFileInput: filList length = 0', async(() => {
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.gridMeasureDetail.statusId = Globals.STATUS.APPLIED;
component.readOnlyForm = false;
// specs compliant (as of March 2018 only Chrome)
// Firefox < 62 workaround exploiting https://bugzilla.mozilla.org/show_bug.cgi?id=1422655
const fileList = new ClipboardEvent('').clipboardData || new DataTransfer();
component.handleFileInput(fileList.files);
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.fileSelected).toBeFalsy();
});
}));
it('should fail on handleFileInput: no file', async(() => {
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.gridMeasureDetail.statusId = Globals.STATUS.APPLIED;
component.readOnlyForm = false;
component.handleFileInput(undefined);
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.fileSelected).toBeFalsy();
});
}));
it('should handle error while delete attached document', async(() => {
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.gridMeasureDetail.statusId = Globals.STATUS.NEW;
component.readOnlyForm = false;
spyOn(component, 'deleteDocument').and.callThrough();
spyOn(toasterMessageService, 'showError').and.callThrough();
component.listOfDocuments = DOCUMENTS;
mockDocService.error = 'process error';
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
const button = fixture.debugElement.nativeElement.querySelector('span.remove');
button.click();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(toasterMessageService.showError).toHaveBeenCalled();
expect(component.showSpinnerFileUpload).toBeFalsy();
});
});
}));
it('should handle a wrong filetype and size correctly', fakeAsync(() => {
spyOn(toasterMessageService, 'showWarn').and.callThrough();
component.Globals.MAX_UPLOADFILE_SIZE = 0;
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[0]));
component.fileToUpload = new File(['testfile'], 'testfile.app', {
type: 'application/*'
});
let returnValue = true;
fixture.detectChanges();
tick();
returnValue = (component as any).fileTypeCheck();
tick();
expect(returnValue).toBeFalsy();
expect(toasterMessageService.showWarn).toHaveBeenCalled();
returnValue = true;
fixture.detectChanges();
tick();
returnValue = (component as any).fileSizeCheck();
tick();
expect(returnValue).toBeFalsy();
expect(toasterMessageService.showWarn).toHaveBeenCalled();
}));
xit('should upload attached document', async(() => {
fixture.detectChanges();
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.gridMeasureDetail.statusId = Globals.STATUS.APPLIED;
// specs compliant (as of March 2018 only Chrome)
// Firefox < 62 workaround exploiting https://bugzilla.mozilla.org/show_bug.cgi?id=1422655
const fileList = new ClipboardEvent('').clipboardData || new DataTransfer();
const fileMock = new File(['foo'], 'programmatically_created.pdf', { type: 'application/pdf' });
fileList.items.add(fileMock);
spyOn(component, 'uploadDocument').and.callThrough();
fixture.detectChanges();
fixture.whenRenderingDone().then(() => {
fixture.detectChanges();
component.handleFileInput(fileList.files);
fixture.detectChanges();
fixture.whenRenderingDone().then(() => {
fixture.detectChanges();
const button = fixture.debugElement.nativeElement.querySelector('upload-buttons.button');
button.click();
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.uploadDocument).toHaveBeenCalled();
});
});
});
}));
it('should process upload gridmeasure attachment correctly', fakeAsync(() => {
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.gridMeasureDetail.statusId = Globals.STATUS.NEW;
component.documentToUpload = new Document();
mockDocService.content = { dummyret: 1 };
(component as any).processUpload();
tick();
expect(component.showSpinnerGridFileUpload).toBeFalsy();
expect(component.fileSelected).toBeFalsy();
}));
it('should handle error while process upload correctly', fakeAsync(() => {
spyOn(console, 'log').and.callThrough();
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.gridMeasureDetail.statusId = Globals.STATUS.NEW;
component.documentToUpload = new Document();
mockDocService.error = 'process error';
(component as any).processUpload();
tick();
expect(component.showSpinnerGridFileUpload).toBeFalsy();
expect(console.log).toHaveBeenCalled();
}));
it('should download attached document', async(() => {
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.gridMeasureDetail.statusId = Globals.STATUS.NEW;
component.listOfDocuments = DOCUMENTS;
mockDocService.content = DOCUMENTS[0];
spyOn(component, 'downloadDocument').and.callThrough();
spyOn(FileSaver, 'saveAs').and.stub();
// (component as any).onReceiveGridMeasureDetail();
fixture.detectChanges();
fixture.whenRenderingDone().then(() => {
fixture.detectChanges();
const button = fixture.debugElement.nativeElement.querySelector('span.download');
button.click();
fixture.detectChanges();
expect(component.downloadDocument).toHaveBeenCalled();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(FileSaver.saveAs).toHaveBeenCalled();
});
});
}));
it('should handle error while downloading an attached document', async(() => {
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.gridMeasureDetail.statusId = Globals.STATUS.NEW;
mockDocService.content = undefined;
mockDocService.error = 'Error while downloading Doc';
component.listOfDocuments = DOCUMENTS;
spyOn(component, 'downloadDocument').and.callThrough();
spyOn(FileSaver, 'saveAs').and.stub();
fixture.detectChanges();
fixture.whenRenderingDone().then(() => {
fixture.detectChanges();
const button = fixture.debugElement.nativeElement.querySelector('span.download');
button.click();
fixture.detectChanges();
expect(component.downloadDocument).toHaveBeenCalled();
expect(component.showSpinnerGridFileUpload).toBeFalsy();
});
}));
const customTestTimeout: number = 1 * 60 * 1000; // explicitly set for readabilty
it('should set time correctly', async(() => {
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.gridMeasureDetail.statusId = Globals.STATUS.NEW;
component.readOnlyForm = false;
const mockDate = new Date().toISOString();
component.gridMeasureDetail.id = undefined;
component.gridMeasureDetail.appointmentStartdate = undefined;
component.gridMeasureDetail.plannedStarttimeFirstSequence = undefined;
component.gridMeasureDetail.plannedEndtimeLastSinglemeasure = undefined;
component.gridMeasureDetail.plannedEndtimeGridmeasure = undefined;
component.gridMeasureDetail.plannedStarttimeFirstSinglemeasure = undefined;
component.setCurrTimeIfEmpty(component.gridMeasureDetail);
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.gridMeasureDetail.appointmentStartdate.substr(0, 16)).toBe(mockDate.substr(0, 16));
expect(component.gridMeasureDetail.plannedStarttimeFirstSequence.substr(0, 16)).toBe(mockDate.substr(0, 16));
expect(component.gridMeasureDetail.plannedEndtimeLastSinglemeasure.substr(0, 16)).toBe(mockDate.substr(0, 16));
expect(component.gridMeasureDetail.plannedEndtimeGridmeasure.substr(0, 16)).toBe(mockDate.substr(0, 16));
expect(component.gridMeasureDetail.plannedStarttimeFirstSinglemeasure.substr(0, 16)).toBe(mockDate.substr(0, 16));
});
}), customTestTimeout);
it('should set appointment times after changes on gridMeasureDetail', () => {
spyOn(component, 'setCurrTimeIfEmpty').and.callThrough();
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
fixture.detectChanges();
component.ngOnChanges({
gridMeasureDetail: new SimpleChange(component.gridMeasureDetail, true, true)
});
fixture.detectChanges();
expect(component.setCurrTimeIfEmpty).toHaveBeenCalled();
});
it('should call getDocumentsForId after changes on id', () => {
spyOn((component as any), 'getDocumentsForId').and.callThrough();
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.id = 3333;
fixture.detectChanges();
component.ngOnChanges({
id: new SimpleChange(component.id, true, true)
});
fixture.detectChanges();
expect((component as any).getDocumentsForId).toHaveBeenCalled();
});
it('should call getDocumentsForId after changes on id with error in documentservice', () => {
spyOn((component as any), 'getDocumentsForId').and.callThrough();
spyOn(console, 'log').and.callThrough();
mockDocService.error = 'Error in Documentservice';
component.gridMeasureDetail = JSON.parse(JSON.stringify(gridmeasures[2]));
component.id = 666;
fixture.detectChanges();
component.ngOnChanges({
id: new SimpleChange(component.id, true, true)
});
fixture.detectChanges();
expect((component as any).getDocumentsForId).toHaveBeenCalled();
expect(console.log).toHaveBeenCalled();
});
});