This is my function,
downloadPdf(event: any) {
if (event.url) {
const file = new Blob([event.url], {type: 'text/plain'});
FileSaver.saveAs(file,'receipt.pdf');
} else {
this.alertService.showAlert(AlertType.ERROR, "Receipt URL not Found!");
throw new Error();
}
}
This is the HTML code for the button,
<ng-template pTemplate="body" let-record>
<tr>
<td *ngFor="let column of tableColumns">
<div>
<button pButton
type="button"
label="Download"
class="p-button-raised p-button-success"
(click)="downloadPdf(record)"
>
</button>
</div>
</td>
</tr>
</ng-template>
The record contains the byte array and some other details. This is the unit test I have written,
it('downloadPdf when no url present', () => {
const event = {
url: null
}
component.downloadPdf(event);
expect(alertServiceMock.showAlert).toHaveBeenCalled();
});
I receive a byte array in the URL attribute and the code is working fine. When I run the unit test for the else condition it fails.
Error thrown
Error:
at BalanceReportComponent../src/app/widgets/balance-report/balancereport.component.ts.BalanceReportComponent.downloadPdf (http://localhost:9876/_karma_webpack_/src/app/widgets/balance-report/balance-report.component.ts:174:13)
at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/widgets/balance-report/balance-report.component.spec.ts:205:15)
at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone.js:386:1)
at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:292:1)
at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone.js:385:1)
at Zone../node_modules/zone.js/dist/zone.js.Zone.run (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone.js:143:1)
at runInTestZone (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:545:1)
at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:560:1)
at <Jasmine>
How should I write a proper unit test for the second condition in my function?