1

I have a component which makes use of a service. I customized what happens when the service throws an error by catching the error and throwing a new one with custom message. I've managed to come up with the below UT, but there are 2 problems with it:

  1. The test passes regardless of what string I write in the expect();
  2. The new error thrown in the original code is not caught, and is displayed in jasmine console:/

How to fix UT for the below piece of code?

new-order.component.ts:

addNew(item: number) {
  this.service.add(item).subscribe(
     res => {
       this.sendNoti(item);
     },
     err => {
        throw new Error(`Item no ${item} was not added to the DB`);
     }
}

new-order.component.spec.ts

orderMockService.add.and.returnValue(throwError({status:500}));
try {
  component.addNew(4);
} catch (err) {
  expect(orderMockService.add).toThrowError(`Item no ${item} was not added  to the DB`);
}

morrigannn
  • 69
  • 1
  • 7

1 Answers1

0

Try this:

orderMockService.add.and.returnValue(throwError({status:500}));
expect((function() { orderMockService.addNew(4); } )).toThrowError(`Item no ${item} was not added  to the DB`);
Ritesh Waghela
  • 3,474
  • 2
  • 19
  • 25