After defining a custom error class called CustomError
:
export class CustomError extends Error {
constructor(message?: string) {
super(message);
Object.setPrototypeOf(this, CustomError.prototype);
}
}
I want to throw instances of CustomError
from an Angular component:
@Component({
moduleId: 'module.id',
templateUrl: 'my.component.html'
})
export class MyComponent {
someMethod(): void {
throw new CustomError();
}
}
To test if CustomError
is thrown, I have created the following test:
describe('MyComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent]
}).compileComponents();
}));
beforeEach(async(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
}));
it('throws CustomError', () => {
expect(component.someMethod).toThrowError(CustomError);
});
});
The above test passes successfully. But when I add a property named someProperty
to MyComponent
like this:
@Component({
moduleId: 'module.id',
templateUrl: 'my.component.html'
})
export class MyComponent {
someProperty: string = "Why does this break it?";
someMethod(): void {
console.log(this.someProperty); // This breaks it, why?
throw new CustomError();
}
}
And try to use that property within the function under test (in this case trying to write to the console), my test fails with a TypeError
:
Expected function to throw AuthError, but it threw TypeError.
at Object.<anonymous> (webpack:///src/app/auth/login/login.component.spec.ts:46:32 <- config/karma-test-shim.js:68955:33) [ProxyZone]
...
This unexpected TypeError
and failure in the test occurs when processing the introduced someProperty
. The issue seems to be related to how someProperty
is handled within the component's function.