0
我已經定義了一個CustomError
作爲測試角分量引發Error失敗,類型錯誤
export class CustomError extends Error {
constructor(message?: string) {
super(message);
Object.setPrototypeOf(this, CustomError.prototype);
}
}
,我想從角分量扔CustomError
,例如
@Component({
moduleId: 'module.id',
templateUrl: 'my.component.html'
})
export class MyComponent {
someMethod(): void {
throw new CustomError();
}
}
現在我想測試CustomError
被拋出,所以我寫了下面的測試
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);
});
});
該測試按預期通過。但是,如果現在我來介紹someProperty
爲MyComponent
,即
@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();
}
}
,並嘗試使用在我測試功能屬性(在這種情況下寫入控制檯),因爲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]
at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:79:0 <- config/karma-test-shim.js:65355:39) [ProxyZone]
at Object.<anonymous> (webpack:///~/zone.js/dist/jasmine-patch.js:104:0 <- config/karma-test-shim.js:65071:34) [ProxyZone]
at webpack:///~/@angular/core/@angular/core/testing.es5.js:96:0 <- config/karma-test-shim.js:20767:17 [ProxyZone]
at AsyncTestZoneSpec.onInvoke (webpack:///~/zone.js/dist/async-test.js:49:0 <- config/karma-test-shim.js:64666:39) [ProxyZone]
at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:76:0 <- config/karma-test-shim.js:65352:39) [ProxyZone]
at AsyncTestZoneSpec._finishCallback (webpack:///~/@angular/core/@angular/core/testing.es5.js:91:0 <- config/karma-test-shim.js:20762:25) [<root>]
at webpack:///~/zone.js/dist/async-test.js:38:0 <- config/karma-test-shim.js:64655:31 [<root>]
at timer (webpack:///~/zone.js/dist/zone.js:1732:0 <- config/karma-test-shim.js:67191:29) [<root>]
爲什麼這會拋出TypeError
並打破我的測試?
它不應該是'的console.log(this.someProperty)'? – adiga
@adiga是的,這是一個錯字。測試仍然失敗。 –