How to write tests for super in custom error class (Typescript)

Solution for How to write tests for super in custom error class (Typescript)
is Given Below:

I am writing test for custom error class and want to cover all lines, but I am not sure how to test super call, also I want to return the barcode provided to object when creation.

export class BarcodeDecoderError extends Error {
  constructor(
    message: string,
    public readonly barcode: string,
    public readonly errorType: ErrorType
  ) {
    super(message);
  }
}

Writing a test should be pretty straightforward. Coverage means “Does this line get executed while running my tests”. So calling the constructor of BarcodeDecoderError should do the trick. Of course you’ll probably also want to test, if the super call has the desired effect:

it('instantiates BarcodeDecoderError with all properties', () => {
    const error = new BarcodeDecoderError('message', 'barcode', ErrorType.Something);
    expect(error.message),toBe('message'); // Test if super call worked
    expect(error.barcode).toBe('barcode');
    expect(error.errorType).toBe(ErrorType.Something);
})

(possibly adjust to your test framework)


Having full coverage usually only becomes a problem when branches are involved (if, switch/case, conditional loops), or if you are building a library exposing functions not used in your code.

In your specific example, it might be enough to test the BarcodeDecoderError in an actual example and have coverage as a byproduct:

it('throws BarcodeDecoderError with all properties', () => {
    // Decode something where you would expect an error
    const decoder = new BarcodeDecoder();
    expect(decoder.decode()).toThrow(expect.objectContaining({
        message: 'message',
        barcode: 'barcode',
        errorType: ErrorType.Something
    }))
})