Summary Table

Categories Total Count
PII 0
URL 0
DNS 0
EKL 0
IP 0
PORT 0
VsID 0
CF 0
AI 6
VPD 0
PL 0
Other 0

File Content

import { FormBuilder } from '@angular/forms';
import { AttachmentViewerComponent } from './attachment-viewer.component';
import { Search275Service } from '../../ars/search275/search275.service';
import { AttachmentViewerService } from './attachment-viewer.service';
import { AuthenticationService } from '../../auth/auth.service';
import { WindowRefService } from '../../window-ref.service';

import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';

const logdbg = console.log; // do logging
// const logdbg = (...args) => {}; // do nothing

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

let search275Service: Search275Service;
let attachmentViewerService: AttachmentViewerService;
let authenticationService: AuthenticationService;
let formBuilder: FormBuilder;
let sanitizer;
let location;
let _window: WindowRefService;
let document;
let route;

beforeEach(() => {
search275Service = new Search275Service(null);
attachmentViewerService = new AttachmentViewerService(null);
formBuilder = new FormBuilder();
authenticationService = new AuthenticationService(null, null, null, null);
sanitizer = { bypassSecurityTrustResourceUrl: () => true };
location = new Observable((observer: Observer<{}>) => observer.next({}));
// _window = new WindowRefService();
_window = {
nativeWindow: {
print: () => true,
scrollTo: () => true,
open: () => true,
// more fakery
history: {pushState: () => true},
navigator: {msSaveOrOpenBlob: () => true},
URL: {
createObjectURL: () => true
}
}
};

document = {
body: {
style: { overflow: '' },
execCommand: command => {
return true;
}
},
execCommand: () => true
};

route = {
snapshot: {
queryParams: () => true
}
};

component = new AttachmentViewerComponent(
sanitizer,
document,
formBuilder,
attachmentViewerService,
authenticationService,
location,
_window,
route
);

jasmine.clock().install();
});

afterEach(() => {
jasmine.clock().uninstall();
});

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

it('test ngOnInit method: exportPermission, editPermission, roleAdmin with userInfoReturned = undefined', () => {
const userInfoReturned = undefined;

spyOn(component, 'formInit');
spyOn(component, 'setLocation');

spyOn(authenticationService, 'getDecodedUserInfo').and.callFake(
() => userInfoReturned
);

expect(component.userInfo).toEqual(undefined);
expect(component.exportPermission).toEqual(false);
expect(component.editPermission).toEqual(false);
expect(component.roleAdmin).toEqual(false);

component.exportPermission = true;
component.editPermission = true;
component.roleAdmin = true;

route.snapshot.queryParams = undefined;

component.ngOnInit();

expect(component.userInfo).toEqual(userInfoReturned);
// expect(component.permissions).toEqual(userInfoReturned.permissions); // no longer used
// since component.userInfo was undefined, expect no change to permissions and roles.
expect(component.exportPermission).toEqual(true);
expect(component.editPermission).toEqual(true);
expect(component.roleAdmin).toEqual(true);
});

it('test ngOnInit method: exportPermission, editPermission, roleAdmin with userInfoReturned = {}', () => {
spyOn(component, 'formInit');
spyOn(component, 'setLocation');

const userInfoReturned = {};
spyOn(authenticationService, 'getDecodedUserInfo').and.callFake(
() => userInfoReturned
);

expect(component.userInfo).toEqual(undefined);
expect(component.exportPermission).toEqual(false);
expect(component.editPermission).toEqual(false);
expect(component.roleAdmin).toEqual(false);

component.exportPermission = true;
component.editPermission = true;
component.roleAdmin = true;

route.snapshot.queryParams = undefined;

component.ngOnInit();

expect(component.userInfo).toEqual(userInfoReturned);
// expect(component.permissions).toEqual(userInfoReturned.permissions); // no longer used
// since component.userInfo was undefined, expect no change to permissions and roles.
expect(component.exportPermission).toEqual(true);
expect(component.editPermission).toEqual(true);

expect(component.userInfo.userRoles).toBeUndefined(); // roleAdmin is set false if component.userInfo exists but component.userInfo.userRoles is falsy
expect(component.roleAdmin).toEqual(false); // roleAdmin is set false if component.userInfo exists but component.userInfo.userRoles is falsy
});

it('test ngOnInit method: exportPermission, editPermission, roleAdmin with userInfoReturned.permissions: {}', () => {
spyOn(component, 'formInit');
spyOn(component, 'setLocation');

const userInfoReturned = {
permissions: {}
};
spyOn(authenticationService, 'getDecodedUserInfo').and.callFake(
() => userInfoReturned
);

expect(component.userInfo).toEqual(undefined);
// expect(component.exportPermission).toEqual(false);
// expect(component.editPermission).toEqual(false);
expect(component.roleAdmin).toEqual(false);

component.exportPermission = true;
component.editPermission = true;
component.roleAdmin = true;

route.snapshot.queryParams = undefined;

component.ngOnInit(); // don't die!

expect(component.userInfo).toEqual(userInfoReturned);
// expect(component.permissions).toEqual(userInfoReturned.permissions); // no longer used
// since component.userInfo was undefined, expect no change to permissions and roles.
// expect(component.exportPermission).toEqual(
// userInfoReturned.permissions['viewAttachment']['exportPermission']
// ); // Actually, undefined
// expect(component.exportPermission).toBeUndefined();
// expect(component.editPermission).toEqual(undefined); // another way

expect(component.userInfo.userRoles).toBeUndefined(); // roleAdmin is set false if component.userInfo exists but component.userInfo.userRoles is falsy
expect(component.roleAdmin).toEqual(false); // roleAdmin is set false if component.userInfo exists but component.userInfo.userRoles is falsy
});

it('test ngOnInit method: {exportPermission, editPermission} = {false, true}', () => {
spyOn(component, 'formInit');
spyOn(component, 'setLocation');

const userInfoReturned = {
permissions: {
viewAttachment: {
exportPermission: false,
editPermission: true
}
}
};
spyOn(authenticationService, 'getDecodedUserInfo').and.callFake(
() => userInfoReturned
);

expect(component.userInfo).toEqual(undefined);
expect(component.exportPermission).toEqual(false);
expect(component.editPermission).toEqual(false);
expect(component.roleAdmin).toEqual(false);

component.exportPermission = true;
component.editPermission = false;
component.roleAdmin = false;

route.snapshot.queryParams = undefined;

component.ngOnInit(); // don't die!

expect(component.userInfo).toEqual(userInfoReturned);
// expect(component.permissions).toEqual(userInfoReturned.permissions); // no longer used
// since component.userInfo was undefined, expect no change to permissions and roles.
expect(component.exportPermission).toEqual(false);
expect(component.editPermission).toEqual(true);

expect(component.userInfo.userRoles).toBeUndefined(); // roleAdmin is set false if component.userInfo exists but component.userInfo.userRoles is falsy
expect(component.roleAdmin).toEqual(false); // roleAdmin is set false if component.userInfo exists but component.userInfo.userRoles is falsy
});

it('test ngOnInit method: {exportPermission, editPermission} = {true, false}', () => {
spyOn(component, 'formInit');
spyOn(component, 'setLocation');

const userInfoReturned = {
permissions: {
viewAttachment: {
exportPermission: true,
editPermission: false
}
}
};
spyOn(authenticationService, 'getDecodedUserInfo').and.callFake(
() => userInfoReturned
);

expect(component.userInfo).toEqual(undefined);
expect(component.exportPermission).toEqual(false);
expect(component.editPermission).toEqual(false);
expect(component.roleAdmin).toEqual(false);

component.exportPermission = false;
component.editPermission = true;
component.roleAdmin = false;

route.snapshot.queryParams = undefined;

component.ngOnInit(); // don't die!

expect(component.userInfo).toEqual(userInfoReturned);
// expect(component.permissions).toEqual(userInfoReturned.permissions); // no longer used
// since component.userInfo was undefined, expect no change to permissions and roles.
expect(component.exportPermission).toEqual(true);
expect(component.editPermission).toEqual(false);

expect(component.userInfo.userRoles).toBeUndefined(); // roleAdmin is set false if component.userInfo exists but component.userInfo.userRoles is falsy
expect(component.roleAdmin).toEqual(false); // roleAdmin is set false if component.userInfo exists but component.userInfo.userRoles is falsy
});

it('test ngOnInit method: userRoles: no ADMIN', () => {
spyOn(component, 'formInit');
spyOn(component, 'setLocation');

const userInfoReturned = {
userRoles: ['USER_ROLE_1', 'USER_ROLE_2', 'USER_ROLE_3'],
permissions: {
viewAttachment: {
exportPermission: true,
editPermission: false
}
}
};
spyOn(authenticationService, 'getDecodedUserInfo').and.callFake(
() => userInfoReturned
);

expect(component.userInfo).toEqual(undefined);
expect(component.exportPermission).toEqual(false);
expect(component.editPermission).toEqual(false);
expect(component.roleAdmin).toEqual(false);

component.exportPermission = false;
component.editPermission = true;
component.roleAdmin = true;

route.snapshot.queryParams = undefined;

component.ngOnInit(); // don't die!

expect(component.userInfo).toEqual(userInfoReturned);
// expect(component.permissions).toEqual(userInfoReturned.permissions); // no longer used
// since component.userInfo was undefined, expect no change to permissions and roles.
expect(component.exportPermission).toEqual(true);
expect(component.editPermission).toEqual(false);

expect(component.roleAdmin).toEqual(false); // roleAdmin is set false if no "ADMIN" role
});

it('test ngOnInit method: userRoles: ADMIN', () => {
spyOn(component, 'formInit');
spyOn(component, 'setLocation');

const userInfoReturned = {
userRoles: ['USER_ROLE_1', 'USER_ROLE_2', 'USER_ROLE_3', 'ARS_ADMIN'],
permissions: {
viewAttachment: {
exportPermission: true,
editPermission: false
}
}
};
spyOn(authenticationService, 'getDecodedUserInfo').and.callFake(
() => userInfoReturned
);

expect(component.userInfo).toEqual(undefined);
expect(component.exportPermission).toEqual(false);
expect(component.editPermission).toEqual(false);
expect(component.roleAdmin).toEqual(false);

component.exportPermission = false;
component.editPermission = true;
component.roleAdmin = true;

route.snapshot.queryParams = undefined;

component.ngOnInit(); // don't die!

expect(component.userInfo).toEqual(userInfoReturned);
// expect(component.permissions).toEqual(userInfoReturned.permissions); // no longer used
// since component.userInfo was undefined, expect no change to permissions and roles.
expect(component.exportPermission).toEqual(true);
expect(component.editPermission).toEqual(false);

expect(component.roleAdmin).toEqual(true); // roleAdmin is set true if "ADMIN" role
});

it('test ngOnInit method: with authenticationService.getDecodedUserInfo returning no "permissions.additionalInformation" property', () => {
spyOn(component, 'formInit');
spyOn(component, 'setLocation');

const userInfoReturned = {
userRoles: ['USER_ROLE_1', 'USER_ROLE_2', 'USER_ROLE_3'],
permissions: {}
};
spyOn(authenticationService, 'getDecodedUserInfo').and.callFake(
() => userInfoReturned
);

expect(component.userInfo).toEqual(undefined);
expect(component.exportPermission).toEqual(false);
expect(component.editPermission).toEqual(false);
expect(component.roleAdmin).toEqual(false);

route.snapshot.queryParams = undefined;

component.ngOnInit();

expect(component.formInit).toHaveBeenCalled();
expect(authenticationService.getDecodedUserInfo).toHaveBeenCalled();
expect(component.setLocation).toHaveBeenCalled();

expect(component.userInfo).toEqual(userInfoReturned);
expect(component.exportPermission).toEqual(false);
expect(component.editPermission).toEqual(false);
expect(component.roleAdmin).toEqual(false);
});

it('test ngOnInit method: "permissions.additionalInformation" is {}', () => {
spyOn(component, 'formInit');
spyOn(component, 'setLocation');

const userInfoReturned = {
userRoles: ['USER_ROLE_1', 'USER_ROLE_2', 'USER_ROLE_3'],
permissions: {
additionalInformation: {}
}
};
spyOn(authenticationService, 'getDecodedUserInfo').and.callFake(
() => userInfoReturned
);

expect(component.userInfo).toEqual(undefined);
expect(component.exportPermission).toEqual(false);
expect(component.editPermission).toEqual(false);
expect(component.roleAdmin).toEqual(false);

route.snapshot.queryParams = undefined;

component.ngOnInit();

expect(component.formInit).toHaveBeenCalled();
expect(authenticationService.getDecodedUserInfo).toHaveBeenCalled();
expect(component.setLocation).toHaveBeenCalled();

expect(component.userInfo).toEqual(userInfoReturned);
// expect(component.permissions).toEqual(userInfoReturned.permissions); // no longer used
expect(component.exportPermission).toEqual(false);
expect(component.editPermission).toEqual(false);
expect(component.roleAdmin).toEqual(false);
});

it('test ngOnInit method: exportPermission, editPermission, roleAdmin with userInfoReturned.permissions missing ', () => {
spyOn(component, 'formInit');
spyOn(component, 'setLocation');

const userInfoReturned = {
userRoles: ['USER_ROLE_1', 'USER_ROLE_2', 'USER_ROLE_3']
// Do not include permissions:, that's what is being tested.
// permissions: {
// additionalInformation: { }
// }
};
spyOn(authenticationService, 'getDecodedUserInfo').and.callFake(
() => userInfoReturned
);

expect(component.userInfo).toEqual(undefined);
expect(component.exportPermission).toEqual(false);
expect(component.editPermission).toEqual(false);
expect(component.roleAdmin).toEqual(false);

component.exportPermission = false;
component.editPermission = false;
component.roleAdmin = false;

route.snapshot.queryParams = undefined;

component.ngOnInit();

expect(component.userInfo).toEqual(userInfoReturned);
// expect(component.permissions).toEqual(userInfoReturned.permissions); // no longer used
expect(component.exportPermission).toEqual(false);
expect(component.editPermission).toEqual(false);
expect(component.roleAdmin).toEqual(false);
});

it('test ngOnChanges method: input "change" parameter has "selectAttachment" and "selectedAttachment.currentValue" properties only', () => {
expect(component.cleanSelectedAttachment).toEqual(null);
component.selectedAttachment = 'SomeSelectedAttachment';
expect(component.selectedAttachmentName).toEqual(null);
expect(document.body.style.overflow).toEqual('');

spyOn(_window.nativeWindow.history, 'pushState');
spyOn(component, 'closeViewer');

// let bypassSecurityTrustResourceUrlReturnValue = 'bypassSecurityTrustResourceUrlReturnValue';
// spyOn(sanitizer, 'bypassSecurityTrustResourceUrl').and.callFake(
// () => bypassSecurityTrustResourceUrlReturnValue
// );

let change;
change = {
selectedAttachment: {
currentValue: '/first/second/third/fourth/last'
}
};
component['location'].path = (includeHash?: boolean) => '/ewv';
component.ngOnChanges(change);

// expect(component.cleanSelectedAttachment).toEqual(bypassSecurityTrustResourceUrlReturnValue);
expect(component.selectedAttachment).toEqual('SomeSelectedAttachment');
// expect(component.selectedAttachmentName).toEqual('last');
expect(document.body.style.overflow).toEqual('');

expect(_window.nativeWindow.history.pushState).not.toHaveBeenCalled();
expect(component.closeViewer).not.toHaveBeenCalled();
// expect(sanitizer.bypassSecurityTrustResourceUrl).toHaveBeenCalled();
// expect(sanitizer.bypassSecurityTrustResourceUrl).toHaveBeenCalledWith('SomeSelectedAttachment');
});

it('test ngOnChanges method: input "change" parameter has "open" and "open.currentValue" properties only', () => {
// expect(component.cleanSelectedAttachment).toEqual(null);
component.selectedAttachment = 'SomeSelectedAttachment';
expect(component.selectedAttachmentName).toEqual(null);
expect(document.body.style.overflow).toEqual('');

// spyOn(_window.nativeWindow.history, 'pushState');
// spyOn(component, 'closeViewer');
spyOn(component, 'onViewAttachment');
spyOn(component, 'setLocation');

// let bypassSecurityTrustResourceUrlReturnValue = 'bypassSecurityTrustResourceUrlReturnValue';
// spyOn(sanitizer, 'bypassSecurityTrustResourceUrl').and.callFake(
// () => bypassSecurityTrustResourceUrlReturnValue
// );

let change;
change = {
open: {
currentValue: '/first/second/third/fourth/last'
}
};
component['location'].path = (includeHash?: boolean) => '/ewv';
component.ngOnChanges(change);

// expect(component.cleanSelectedAttachment).toEqual(undefined);
expect(component.selectedAttachment).toEqual('SomeSelectedAttachment');
// expect(component.selectedAttachmentName).toEqual(null);
expect(document.body.style.overflow).toEqual('hidden');

// expect(_window.nativeWindow.history.pushState).toHaveBeenCalled();
// expect(_window.nativeWindow.history.pushState).toHaveBeenCalledWith({},'ewv', '/ewv');
// expect(component.closeViewer).toHaveBeenCalled();
// expect(sanitizer.bypassSecurityTrustResourceUrl).not.toHaveBeenCalled();
expect(component.onViewAttachment).toHaveBeenCalled();
expect(component.setLocation).toHaveBeenCalled();
});

it('test ngOnChanges method: input "change" parameter has "open", "open.currentValue", "selectAttachment", and "selectedAttachment.currentValue" properties', () => {
// expect(component.cleanSelectedAttachment).toEqual(null);
component.selectedAttachment = 'SomeSelectedAttachment';
expect(component.selectedAttachmentName).toEqual(null);
expect(document.body.style.overflow).toEqual('');

// spyOn(_window.nativeWindow.history, 'pushState');
// spyOn(component, 'closeViewer');

spyOn(component, 'setLocation');
spyOn(component, 'onViewAttachment');

// let bypassSecurityTrustResourceUrlReturnValue = 'bypassSecurityTrustResourceUrlReturnValue';
// spyOn(sanitizer, 'bypassSecurityTrustResourceUrl').and.callFake(
// () => bypassSecurityTrustResourceUrlReturnValue
// );

let change;
change = {
open: {
currentValue: '/first/second/third/fourth/last'
},
selectedAttachment: {
currentValue: '/first/second/third/fourth/last'
}
};
component['location'].path = (includeHash?: boolean) => '/search275';
component.ngOnChanges(change);

// expect(component.cleanSelectedAttachment).toEqual(bypassSecurityTrustResourceUrlReturnValue);
expect(component.selectedAttachment).toEqual('SomeSelectedAttachment');
// expect(component.selectedAttachmentName).toEqual('last');
expect(document.body.style.overflow).toEqual('hidden');

// expect(_window.nativeWindow.history.pushState).toHaveBeenCalled();
// expect(_window.nativeWindow.history.pushState).toHaveBeenCalledWith({},'search275', '/search275');
// expect(component.closeViewer).toHaveBeenCalled();
// expect(sanitizer.bypassSecurityTrustResourceUrl).toHaveBeenCalled();
// expect(sanitizer.bypassSecurityTrustResourceUrl).toHaveBeenCalledWith('SomeSelectedAttachment');
expect(component.setLocation).toHaveBeenCalled();
expect(component.onViewAttachment).toHaveBeenCalled();
});

it('test ngOnChanges method: input "change" parameter has no "open" nor "selectedAttachment" properties', () => {
expect(component.cleanSelectedAttachment).toEqual(null);
component.selectedAttachment = 'SomeSelectedAttachment';
expect(component.selectedAttachmentName).toEqual(null);
expect(document.body.style.overflow).toEqual('');

spyOn(component, 'setLocation');
spyOn(component, 'onViewAttachment');

// spyOn(_window.nativeWindow.history, 'pushState');
// spyOn(component, 'closeViewer');

// let bypassSecurityTrustResourceUrlReturnValue = 'bypassSecurityTrustResourceUrlReturnValue';
// spyOn(sanitizer, 'bypassSecurityTrustResourceUrl').and.callFake(
// () => bypassSecurityTrustResourceUrlReturnValue
// );

let change;
change = {};
component['location'].path = (includeHash?: boolean) => '/ewv';
component.ngOnChanges(change);

// expect(component.cleanSelectedAttachment).toEqual(undefined);
expect(component.selectedAttachment).toEqual('SomeSelectedAttachment');
expect(component.selectedAttachmentName).toEqual(null);
expect(document.body.style.overflow).toEqual('');

// expect(_window.nativeWindow.history.pushState).not.toHaveBeenCalled();
// expect(component.closeViewer).not.toHaveBeenCalled();
// expect(sanitizer.bypassSecurityTrustResourceUrl).not.toHaveBeenCalled();

expect(component.setLocation).not.toHaveBeenCalled();
expect(component.onViewAttachment).not.toHaveBeenCalled();
});

it('test ngOnChanges method: input "change" parameter has "open" and "selectedAttachment" properties, but these properties have no "currentValue" property ', () => {
expect(component.cleanSelectedAttachment).toEqual(null);
component.selectedAttachment = 'SomeSelectedAttachment';
expect(component.selectedAttachmentName).toEqual(null);
expect(document.body.style.overflow).toEqual('');

// spyOn(_window.nativeWindow.history, 'pushState');
// spyOn(component, 'closeViewer');

spyOn(component, 'setLocation');
spyOn(component, 'onViewAttachment');

// let bypassSecurityTrustResourceUrlReturnValue = 'bypassSecurityTrustResourceUrlReturnValue';
// spyOn(sanitizer, 'bypassSecurityTrustResourceUrl').and.callFake(
// () => bypassSecurityTrustResourceUrlReturnValue
// );

let change;
change = {
cleanSelectedAttachment: {},
open: {}
};
component.ngOnChanges(change);

// expect(component.cleanSelectedAttachment).toEqual(undefined);
// expect(component.selectedAttachment).toEqual('SomeSelectedAttachment');
// expect(component.selectedAttachmentName).toEqual(null);
expect(document.body.style.overflow).toEqual('');

// expect(_window.nativeWindow.history.pushState).not.toHaveBeenCalled();
// expect(component.closeViewer).not.toHaveBeenCalled();
// expect(sanitizer.bypassSecurityTrustResourceUrl).not.toHaveBeenCalled();

expect(component.setLocation).not.toHaveBeenCalled();
expect(component.onViewAttachment).not.toHaveBeenCalled();
});

it('test closeViewer method', () => {
component.formInit();

component.fileExtension = 'extension';
component.cleanSelectedAttachment = 'CleanSelectedAttachgment';
document.body.style.overflow = '';
component.attachmentModified = true;
component.associateView = true;

spyOn(component.form, 'reset');
spyOn(component, 'reset');
spyOn(component.notify, 'emit');

const viewerNotify = {
open: false,
updateTable: component.attachmentModified
};

component.closeViewer();

expect(component.fileExtension).toEqual(null);
expect(component.cleanSelectedAttachment).toEqual(null);
expect(document.body.style.overflow).toEqual('visible');
expect(component.attachmentModified).toEqual(false);
expect(component.associateView).toEqual(false);

expect(component.form.reset).toHaveBeenCalled();
expect(component.reset).toHaveBeenCalled();
expect(component.notify.emit).toHaveBeenCalled();
expect(component.notify.emit).toHaveBeenCalledWith(viewerNotify);
});

it('test viewAssociateForm method: "component.associateView" is boolean false', () => {
component.formInit();
component.associateView = false;
component.form.controls['unmatched837Id'].setValue('1234');

component.viewAssociateForm();

expect(component.associateView).toBe(true);
expect(component.failed).toEqual(false);
expect(component.form.get('unmatched837Id').value).toEqual('1234');
});

it('test viewAssociateForm method: "component.associateView" is boolean true', () => {
component.formInit();
component.associateView = true;
component.form.controls['unmatched837Id'].setValue('1234');

component.viewAssociateForm();

expect(component.associateView).toBe(false);
expect(component.failed).toEqual(false);
expect(component.form.get('unmatched837Id').value).toEqual(null);
});

it('test onArchiveView method', () => {
component.modalView = false;
component.onArchiveView();
expect(component.modalView).toBe(true);
});

it('test onModalClose method', () => {
component.modalView = true;
component.onModalClose();
expect(component.modalView).toBe(false);
});

it('test onArchive method -- skip', () => {
// component.onArchive();
});

it('test reActivate method -- skip', () => {
// component.reActivate();
});

it('test formInit method: form should be initialized', () => {
expect(component.form).toEqual(undefined);

component.formInit();

expect(component.form).toBeDefined();
expect(component.form).not.toBeNull();
});

it('test formInit method: verify that initially the form is in the invalid state', () => {
component.formInit();

expect(component.form.get('unmatched837Id').valid).toEqual(false);
expect(component.form.valid).toEqual(false);
});

it('test formInit method: invalid form if "unmatched837Id" value is an empty string', () => {
component.formInit();

component.form.get('unmatched837Id').setValue('');

expect(component.form.get('unmatched837Id').valid).toEqual(false);
expect(component.form.valid).toEqual(false);
});

it('test formInit method: invalid form if "unmatched837Id" value has any characters that are not numbers', () => {
component.formInit();

component.form.get('unmatched837Id').setValue('6789iop');

expect(component.form.get('unmatched837Id').valid).toEqual(false);
expect(component.form.valid).toEqual(false);
});

it('test formInit method: valid form if "unmatched837Id" value has all numbers', () => {
component.formInit();

component.form.get('unmatched837Id').setValue('6789');

expect(component.form.get('unmatched837Id').valid).toEqual(true);
expect(component.form.valid).toEqual(true);
});

it('test reset method', () => {
expect(component.downloadDoc).toEqual(false);
expect(component.downloadRtf).toEqual(false);

component.reset();

expect(component.downloadDoc).toEqual(false);
expect(component.downloadRtf).toEqual(false);

component.reset();

expect(component.downloadDoc).toEqual(false);
expect(component.downloadRtf).toEqual(false);
});

it('test ngOnDestroy method viewedXml = true', () => {
spyOn(component.subscription, 'unsubscribe');
spyOn(attachmentViewerService, 'cleanXmlTempFolder').and.returnValue(
Observable.of({ message: 'MESSAGE' })
);
component.viewedXml = true;
component.ngOnDestroy();

expect(document.body.style.overflow).toEqual('visible');
expect(component.subscription.unsubscribe).toHaveBeenCalled();
expect(attachmentViewerService.cleanXmlTempFolder).toHaveBeenCalled();
});

it('test ngOnDestroy method viewedXml = false', () => {
spyOn(component.subscription, 'unsubscribe');
spyOn(attachmentViewerService, 'cleanXmlTempFolder').and.returnValue(
Observable.of({ message: 'MESSAGE' })
);

component.viewedXml = false;
component.ngOnDestroy();

expect(document.body.style.overflow).toEqual('visible');
expect(component.subscription.unsubscribe).toHaveBeenCalledTimes(0);
expect(attachmentViewerService.cleanXmlTempFolder).toHaveBeenCalledTimes(0);
});

it('test onSubmit method: "attachmentService.match" returns back data that has a "response" property', () => {
component.formInit();

component.attachKey = {
attachIdLx: '',
status: ''
};

expect(component.attachmentModified).toEqual(false);
expect(component.success).toEqual(undefined);
expect(component.associateView).toEqual(false);

expect(component.failed).toEqual(undefined);
expect(component.errorDescription).toEqual(null);

spyOn(component.subscription, 'add');

const returnedMatchData = { response: {} };
spyOn(attachmentViewerService, 'match').and.callFake(
() =>
new Observable((observer: Observer<{}>) =>
observer.next(returnedMatchData)
)
);

component.onSubmit();

jasmine.clock().tick(500);
expect(component.success).toEqual(true);

jasmine.clock().tick(7001);
expect(component.success).toEqual(false);

expect(component.attachmentModified).toEqual(true);
expect(component.associateView).toEqual(false);

expect(component.failed).toEqual(undefined);
expect(component.errorDescription).toEqual(null);

expect(component.subscription.add).toHaveBeenCalled();
expect(attachmentViewerService.match).toHaveBeenCalled();
});

it('test onSubmit method: "attachmentService.match" returns back data that has no "response" property', () => {
component.formInit();

component.attachKey = {
attachIdLx: '',
status: ''
};

expect(component.attachmentModified).toEqual(false);
expect(component.success).toEqual(undefined);
expect(component.associateView).toEqual(false);

expect(component.failed).toEqual(undefined);
expect(component.errorDescription).toEqual(null);

spyOn(component.subscription, 'add');

const returnedMatchData = {};
spyOn(attachmentViewerService, 'match').and.callFake(
() =>
new Observable((observer: Observer<{}>) =>
observer.next(returnedMatchData)
)
);

component.onSubmit();

jasmine.clock().tick(500);
expect(component.success).toEqual(undefined);

jasmine.clock().tick(7001);
expect(component.success).toEqual(undefined);

expect(component.attachmentModified).toEqual(true);
expect(component.associateView).toEqual(false);

expect(component.failed).toEqual(undefined);
expect(component.errorDescription).toEqual(null);

expect(component.subscription.add).toHaveBeenCalled();
expect(attachmentViewerService.match).toHaveBeenCalled();
});

it('test onSubmit method: "attachmentService.match" returns back error response', () => {
component.formInit();

component.attachKey = {
attachIdLx: '',
status: ''
};

expect(component.attachmentModified).toEqual(false);
expect(component.success).toEqual(undefined);
expect(component.associateView).toEqual(false);

expect(component.failed).toEqual(undefined);
expect(component.errorDescription).toEqual(null);

spyOn(component.subscription, 'add');

const returnedMatchErrorData = {
_body: JSON.stringify({ message: 'ERROR MESSAGE' })
};
spyOn(attachmentViewerService, 'match').and.returnValue(
Observable.throw(returnedMatchErrorData)
);

component.onSubmit();

expect(component.success).toEqual(undefined);

expect(component.attachmentModified).toEqual(false);
expect(component.associateView).toEqual(false);

expect(component.failed).toEqual(true);
expect(component.errorDescription).toEqual('ERROR MESSAGE');

expect(component.subscription.add).toHaveBeenCalled();
expect(attachmentViewerService.match).toHaveBeenCalled();
});

// Currently unused, but it may return, do not DELETE
it('attachmentFileName', () => {
const fake = 'fishy.gif'; // currently it fakes out a bad value

expect(component.attachmentFileName(undefined)).toEqual(fake);
expect(component.attachmentFileName('')).toEqual(fake);

'this;that.foo;any.thing.you.want'.split(';').forEach(fil => {
expect(
component.attachmentFileName('attachment; filename=' + fil)
).toEqual(fil);
});
});

// Currently unused
it(`test attachmentFileName on [undefined, '']`, () => {
const fake = 'fishy.gif'; // currently it fakes out a bad value
expect(component.attachmentFileName(undefined)).toEqual(fake);
expect(component.attachmentFileName('')).toEqual(fake);
});

// check on attachmentFileName;
it('test attachmentFileName', () => {
// pure function, doesn't need to be re-started
const files = [
'foo.bar',
'a',
'averylongfilename.with.lots. of dots and [] odd characters!@#$%^&*()',
'even/a/path/name.pdf',
// 'even\a\really\big\name.pdf', // escapes? \n fails to match
'even\\a\\really\\big\\name.pdf'
];
files.forEach(file => {
// Simple filenames are returned unchanged
expect(component.attachmentFileName(file)).toEqual(file);
// matching "attachment;filename=${file}" returns the file
expect(
component.attachmentFileName(`attachment;filename=${file}`)
).toEqual(file);
expect(
component.attachmentFileName(`attachment; filename=${file}`)
).toEqual(file);
expect(
component.attachmentFileName(`attachment; filename=${file}`)
).toEqual(file);
expect(
component.attachmentFileName(`attachment; filename=${file}`)
).toEqual(file);

// erroneous versions return the whole string
const shouldFail = [
`file=${file}`,
`filename=${file}`,
`tachment; filename=${file}`,
`the attachment; filename=${file}`,
`attachment; Filename=${file}`, // it's case-sensitive
`Attachment; Filename=${file}`,
`attachment; file=${file}`,
`attachment; name=${file}`
];
shouldFail.forEach(mess => {
expect(component.attachmentFileName(mess)).toEqual(mess);
});
});
});

it(`test fileTYP should extract extension, toUpperCase()`, () => {
// fileTYP is not intended to handle "path/names.uhoh/foo"
// It won't really matter to us, since we're only interested in file.EXT anyway.
const cases = 'foo=FOO,fishy.gif=GIF,far.far.away=AWAY';
cases.split(',').forEach(test => {
const [arg, res] = test.split('=');
expect(res.toUpperCase()).toEqual(res); // quod custodiet custodiens // Check res to be upper case, just in case.
expect(component.fileTYP(arg)).toEqual(res);
});
});

///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Things to test, extracted from attachment-viewer.component.ts
///////////////////////////////////////////////////////////////////////////////////////////////////////////////


it(`test tabbable => tabIndex`, () => {
const cases = 'ttfft'; // all transitions from bool to bool
// let prev = true;
// expect(component.tabIndex).toEqual('0');
cases.split('').forEach(test => {
const tabb = test === 't';
const tabI = tabb ? '0' : '-1';
component.tabIdx = tabI;
// console.log(
// `tabb= ${tabb}, tabI= ${tabI}, component.tabbable= ${component.tabIdx}`
// );
expect(component.tabIdx).toEqual(tabI);
});
});

// constructor(
// ngOnInit() {
// ngOnChanges(change: SimpleChanges) {
// setLocation() {
// formInit() {
// onSubmit() {
// closeViewer(): void {
// viewAssociateForm(): void {
// onArchiveView(): void {
// onArchive() {
// reActivate() {
// onModalClose(): void {
// reset() {

// done attachmentFileName(contentDisposition: string) {

// done fileTYP(fileName: string) {

// /////////////////////////////////////////////////
// The following calls all involve browser actions that must be mocked
// /////////////////////////////////////////////////

// todo onViewAttachment() SpyOn(attachmentViewerService.viewAttachment)
it('onViewAttachment attachKey', () => {
const fake = 'fishy.gif'; // currently it fakes out a bad value
spyOn(attachmentViewerService, 'viewAttachment'); // not the viewer, but the file getter

const blob = new Blob(['testing 1,2,3']);
const attContentType = 'image/gif';
const attName = 'foo.gif';

// TEST This code
// const attachmentRequest: AttachmentRequest = {
// vhaName: this.userInfo.userName,
// attachIdLx: this.attachIdLx, // naming conflict
// applicationLevel: this.applicationLevel,
// isDownload: true
// };
// this.attachmentViewerService.exportAttachment(attachmentRequest).subscribe(
// (data: Response) => {}, (error) => {});
const userInfoReturned = {
userName:
AI ,
userRoles: ['USER_ROLE_1', 'USER_ROLE_2', 'USER_ROLE_3'],
permissions: {
viewAttachment: {
exportPermission: true,
editPermission: false
}
}
};
component.userInfo = userInfoReturned;

// component.attachIdLx = 'MockId'; // a get function!
component.attachKey = {
attachIdLx: 'MockId',
status: ''
};
component.attachmentViewerLocation = 'ATTACHMENT_VIEWER';
});

it('onViewAttachment imgUrl', () => {
const fake = 'fishy.gif'; // currently it fakes out a bad value
const blobType = 'application/octet-stream';
const attContentType = 'image/gif';
const attName = 'foo.gif';
const attTYP = 'GIF'; // in a forEach, use attName.split('.').pop().toUpperCase();
// Bypass request: it is tested above
const _headers = {
'content-type': attContentType,
'x-attachment-name': attName // node expects lower case!
};
const getHeader = (key: string) => _headers[key.toLowerCase()];
const testBlob = new Blob(['testing 1,2,3'], { type: blobType });
logdbg('testBlob=', testBlob);
logdbg('testBlob.type=', testBlob.type);
const response = {
blob: () => response._blob, // kinda circular
// _blob: {... testBlob},
_blob: testBlob,
headers: {
get: (key: string) => _headers[key.toLowerCase()],
getAll: (key: string) => [_headers[key.toLowerCase()]] // In this case return a single item
}
};
//////////////////////////
// Bypass this code: TESTED ON ITS OWN above.

// logdbg(
// 'onViewAttachment at attachmentViewerLocation',
// this.attachmentViewerLocation
// );
// const attachmentRequest: AttachmentRequest = {
// vhaName: this.userInfo.userName,
// attachIdLx: this.attachIdLx,
// applicationLevel: this.applicationLevel,
// isDownload: false
// };

// logdbg('attachmentRequest', attachmentRequest);
spyOn(attachmentViewerService, 'viewAttachment').and.returnValue(
Observable.of(response)
);

component.exportPermission = true;
component.arsViewer = true;
const userInfoReturned = {
userName:
AI ,
userRoles: ['USER_ROLE_1', 'USER_ROLE_2', 'USER_ROLE_3'],
permissions: {
viewAttachment: {
exportPermission: true,
editPermission: false
}
}
};
component.userInfo = userInfoReturned;
component.attachKey = {
attachIdLx: 'MockId',
status: ''
};

spyOn(_window.nativeWindow.URL, 'createObjectURL').and.callThrough();

//// TEST
component.onViewAttachment();

// this.attachmentViewerService // not the viewer, but the file getter
// .viewAttachment(attachmentRequest) // not the view, but the file get
// .subscribe((data: Response) => {
// // tslint:disable-next-line:no-console
// // logdbg('onViewAttachment data.headers=', data.headers);
// // responseType: ResponseContentType.Blob

// const contentType = data.headers.get('content-type').toString();
// const filename = this.dataGetAttachmentName(data);
// const name = filename.split('/').pop(); // drop any path part
// this.fileExtension = this.fileTYP(name);
expect(component.fileExtension).toBe(attTYP);
// this.selectedAttachmentName = name;
expect(component.selectedAttachmentName).toBe(attName);
// const isImage = isImageExt(this.fileExtension);
// // Now they want to exportAsPDF the XML, too! refactor.
// this.exportAsPDFShow =
// isImage &&
// this.exportPermission &&
// (this.arsViewer || this.fppsViewer);

expect(component.exportAsPDFShow).toBe(true);


const fakeURL = 'fake://url';
expect(_window.nativeWindow.URL.createObjectURL).toHaveBeenCalled();
expect(component.selectedAttachment).toBeNull();
expect(component.cleanSelectedAttachment).toBeNull();
expect(component.xmlSrc).toBeNull();
expect(component.imgSrc).toBe(true); // true? that's strange
// expect(component.imgSrc).toBe(fakeURL); // What I really expected
// }
// });
});

// // todo nonIE_saveAs(blob: Blob, fileName: string)

// todo onExportAttachment()
it('test onExportAttachment unauthorized', () => {
const fake = 'fishy.gif'; // currently it fakes out a bad value
const blobType = 'application/octet-stream';
const attContentType = 'image/gif';
const attName = 'foo.gif';
const attTYP = 'GIF'; // in a forEach, use attName.split('.').pop().toUpperCase();

const _headers = {
'content-type': attContentType,
'x-attachment-name': attName // node expects lower case!
};
const getHeader = (key: string) => _headers[key.toLowerCase()];
const testBlob = new Blob(['testing 1,2,3'], { type: blobType });
logdbg('testBlob=', testBlob);
logdbg('testBlob.type=', testBlob.type);
const response = {
blob: () => response._blob, // kinda circular
// _blob: {... testBlob},
_blob: testBlob,
headers: {
get: (key: string) => _headers[key.toLowerCase()],
getAll: (key: string) => [_headers[key.toLowerCase()]] // In this case return a single item
}
};

spyOn(attachmentViewerService, 'exportAttachment').and.returnValue(
Observable.of(response)
);

spyOn(_window.nativeWindow.navigator, 'msSaveOrOpenBlob'); // .and.callFake(blob, attName);

// const fileName = this.dataGetAttachmentName(data);
// this.fileExtension = this.fileTYP(fileName);

const userInfoReturned = {
userName:
AI ,
userRoles: ['USER_ROLE_1', 'USER_ROLE_2', 'USER_ROLE_3'],
permissions: {
viewAttachment: {
exportPermission: false,
editPermission: false
}
}
};

component.userInfo = userInfoReturned;
component.exportPermission = false; // override ngInit
spyOn(component, 'dataGetAttachmentName').and.callFake((data: Response) => 'att-xxx.gif.pdf');
spyOn(component, 'dataBlobAsType').and.callFake((data: Response) => testBlob);
spyOn(component, 'saveAs');

//// TEST ////
component.onExportAttachment();

// Aborts because component.exportPermission === false;
expect(attachmentViewerService.exportAttachment).not.toHaveBeenCalled();

expect(component.dataGetAttachmentName).not.toHaveBeenCalled();
expect(component.dataBlobAsType).not.toHaveBeenCalled();
expect(component.saveAs).not.toHaveBeenCalled();

expect(_window.nativeWindow.navigator.msSaveOrOpenBlob).not.toHaveBeenCalled();
// Side effects:
expect(component.selectedAttachmentName).toEqual(null);
expect(component.fileExtension).toEqual(null);

});

it('test onExportAttachment authorized', () => {
const fake = 'fishy.gif'; // currently it fakes out a bad value
const blobType = 'application/octet-stream';
const attContentType = 'image/gif';
const attName = 'foo.gif';
const attTYP = 'GIF'; // in a forEach, use attName.split('.').pop().toUpperCase();

const _headers = {
'content-type': attContentType,
'x-attachment-name': attName // node expects lower case!
};
const getHeader = (key: string) => _headers[key.toLowerCase()];
const testBlob = new Blob(['testing 1,2,3'], { type: blobType });
logdbg('testBlob=', testBlob);
logdbg('testBlob.type=', testBlob.type);
const response = {
blob: () => response._blob, // kinda circular
// _blob: {... testBlob},
_blob: testBlob,
headers: {
get: (key: string) => _headers[key.toLowerCase()],
getAll: (key: string) => [_headers[key.toLowerCase()]] // In this case return a single item
}
};

spyOn(attachmentViewerService, 'exportAttachment').and.returnValue(
Observable.of(response)
);

spyOn(_window.nativeWindow.navigator, 'msSaveOrOpenBlob'); // .and.callFake(blob, attName);

const userInfoReturned = {
userName:
AI ,
userRoles: ['USER_ROLE_1', 'USER_ROLE_2', 'USER_ROLE_3'],
permissions: {
viewAttachment: {
exportPermission: true,
editPermission: false
}
}
};
component.attachKey = {
attachIdLx: 'MockId',
status: ''
};
component.userInfo = userInfoReturned; // bypass ngInit
component.exportPermission = true; // override ngInit
spyOn(component, 'dataGetAttachmentName').and.callFake((data: Response) => attName);
spyOn(component, 'dataBlobAsType').and.callFake((data: Response) => testBlob);
spyOn(component, 'saveAs');

//// TEST ////
component.onExportAttachment();

// Because ent.exportPermission = true
expect(attachmentViewerService.exportAttachment).toHaveBeenCalled();

expect(component.dataGetAttachmentName).toHaveBeenCalled();
expect(component.dataBlobAsType).toHaveBeenCalled();
expect(component.saveAs).toHaveBeenCalled();

expect(component.saveAs).toHaveBeenCalledWith(testBlob, component.attachKey.attachIdLx + '-' + attName);
// No callThrough
expect(_window.nativeWindow.navigator.msSaveOrOpenBlob).not.toHaveBeenCalled();

// non Side effects, these belong to viewAttachment, and should not be changed:
expect(component.selectedAttachmentName).toEqual(null);
expect(component.fileExtension).toEqual(null);

});

// todo onExportAsPDF() {
it('test onExportAsPDF unauthorized', () => {
const fake = 'fishy.gif'; // currently it fakes out a bad value
const blobType = 'application/octet-stream';
const attContentType = 'image/gif';
const attName = 'foo.gif';
const attTYP = 'GIF'; // in a forEach, use attName.split('.').pop().toUpperCase();
const _headers = {
'content-type': attContentType,
'x-attachment-name': attName // node expects lower case!
};
const getHeader = (key: string) => _headers[key.toLowerCase()];
const testBlob = new Blob(['testing 1,2,3'], { type: blobType });
logdbg('testBlob=', testBlob);
logdbg('testBlob.type=', testBlob.type);
const response = {
blob: () => response._blob, // kinda circular
// _blob: {... testBlob},
_blob: testBlob,
headers: {
get: (key: string) => _headers[key.toLowerCase()],
getAll: (key: string) => [_headers[key.toLowerCase()]] // In this case return a single item
}
};


spyOn(attachmentViewerService, 'exportAsPDF').and.returnValue(
Observable.of(response)
);

spyOn(_window.nativeWindow.navigator, 'msSaveOrOpenBlob'); // .and.callFake(blob, attName);
const userInfoReturned = {
userName:
AI ,
userRoles: ['USER_ROLE_1', 'USER_ROLE_2', 'USER_ROLE_3'],
permissions: {
viewAttachment: {
exportPermission: false,
editPermission: false
}
}
};
component.userInfo = userInfoReturned;
component.exportPermission = false; // override ngInit
// Here we are using internal details to supply values
// spyOn(component, 'dataGetAttachmentName').and.callFake((data: Response) => 'att-xxx.gif.pdf');
// spyOn(component, 'dataBlobAsType').and.callFake((data: Response) => testBlob);
// We can just return some values
spyOn(component, 'dataGetAttachmentName').and.returnValue('att-xxx.gif.pdf');
spyOn(component, 'dataBlobAsType').and.returnValue(testBlob);
// would it be better to provide more realistic data and let dataGetAttachmentName be called?
spyOn(component, 'saveAs');

//// TEST ////
component.onExportAsPDF();

// Aborts because component.exportPermission === false;
expect(component.dataGetAttachmentName).not.toHaveBeenCalled();
expect(component.dataBlobAsType).not.toHaveBeenCalled();
expect(component.saveAs).not.toHaveBeenCalled();
expect(attachmentViewerService.exportAsPDF).not.toHaveBeenCalled();
expect(_window.nativeWindow.navigator.msSaveOrOpenBlob).not.toHaveBeenCalled();
// non Side effects:
expect(component.selectedAttachmentName).toEqual(null);
expect(component.fileExtension).toEqual(null);

});

it('test onExportAsPDF authorized', () => {
const fake = 'fishy.gif'; // currently it fakes out a bad value
const blobType = 'application/octet-stream';
const attContentType = 'image/gif';
const attName = 'foo.gif';
const attTYP = 'GIF'; // in a forEach, use attName.split('.').pop().toUpperCase();
const _headers = {
'content-type': attContentType,
'x-attachment-name': attName // node expects lower case!
};
const getHeader = (key: string) => _headers[key.toLowerCase()];
const testBlob = new Blob(['testing 1,2,3'], { type: blobType });
logdbg('testBlob=', testBlob);
logdbg('testBlob.type=', testBlob.type);
const response = {
blob: () => response._blob, // kinda circular
// _blob: {... testBlob},
_blob: testBlob,
headers: {
get: (key: string) => _headers[key.toLowerCase()],
getAll: (key: string) => [_headers[key.toLowerCase()]] // In this case return a single item
}
};

spyOn(attachmentViewerService, 'exportAsPDF').and.returnValue(
Observable.of(response)
);

spyOn(_window.nativeWindow.navigator, 'msSaveOrOpenBlob'); // .and.callFake(blob, attName);

const userInfoReturned = {
userName:
AI ,
userRoles: ['USER_ROLE_1', 'USER_ROLE_2', 'USER_ROLE_3'],
permissions: {
viewAttachment: {
exportPermission: true,
editPermission: false
}
}
};
component.userInfo = userInfoReturned; // bypass ngInit
component.exportPermission = true; // override ngInit
spyOn(component, 'dataGetAttachmentName').and.callFake((data: Response) => 'att-xxx.gif.pdf');
spyOn(component, 'dataBlobAsType').and.callFake((data: Response) => testBlob);
spyOn(component, 'saveAs');

//// TEST ////
component.onExportAsPDF();

expect(component.dataGetAttachmentName).toHaveBeenCalled();
expect(component.dataBlobAsType).toHaveBeenCalled();
expect(component.saveAs).toHaveBeenCalledWith(testBlob, 'att-xxx.gif.pdf');
expect(attachmentViewerService.exportAsPDF).toHaveBeenCalled();
// Because spyOn(component, 'saveAs'); msSaveOrOpenBlob is never called
expect(_window.nativeWindow.navigator.msSaveOrOpenBlob).not.toHaveBeenCalled();
// non Side effects:
expect(component.selectedAttachmentName).toEqual(null);
expect(component.fileExtension).toEqual(null);
// Side effects:

});
//// TEST onExportAsPDF for error=> ////

// todo onRightClick(ev) {

// todo ngOnDestroy() {
});