angularunit-testingjasminekarma-jasmineangular-test

Angular / Jasmine Error Messages are not the same--Quoted?


I am trying to run a test using Angular/Jasmine.

Here is my function:

    ValidateX(value : number) {
        if (value > 5) {
          throw new Error('Number is greater than 5');
        }
    } 

Here is my test:

    it('X test', () => {
        expect(function(){service.ValidateX(7);}).toThrow('Number is greater than 5');
      })

Here is my error:

ValidationsService > X test Expected function to throw 'Number is greater than 5', but it threw Error: Number is greater than 5. at at UserContext.apply (http://localhost:9876/karma_webpack/webpack:/src/app/services/validations.service.spec.ts:27:47) at _ZoneDelegate.invoke (http://localhost:9876/karma_webpack/webpack:/node_modules/zone.js/fesm2015/zone.js:369:28) at ProxyZoneSpec.onInvoke (http://localhost:9876/karma_webpack/webpack:/node_modules/zone.js/fesm2015/zone-testing.js:2081:39) at _ZoneDelegate.invoke (http://localhost:9876/karma_webpack/webpack:/node_modules/zone.js/fesm2015/zone.js:368:34)*

I've checked the error messages for extra spaces, I've tried to add quotes to the error message in the function, but nothing works. The error messages appear to be exactly the same, but test is saying that they are not.

What am I missing?


Solution

  • I think it's checking the full error object, instead try toThrowError method.

    toThrowError(expectedopt, messageopt)

    expect a function to throw an Error.

    import { ValidateX } from './identity';
    
    describe('identity', () => {
      it('ValidateX test', () => {
        expect(function () {
          ValidateX(7);
        }).toThrowError(Error, 'Number is greater than 5');
        // .toThrowError('Number is greater than 5'); // <- also works!
      });
    });
    

    If you want to use toThrow, you should pass in an error object with the message like below.

    it('ValidateX test - to throw', () => {
      expect(function () {
        ValidateX(7);
      }).toThrow(new Error('Number is greater than 5'));
    });
    

    Stackblitz Demo