![](/img/trans.png)
[英]Angular component test error: TypeError Cannot read property 'subscribe' of undefined
[英]Test Angular Component Throws Error Fails With TypeError
我已經定義了一個CustomError
為
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
並破壞我的測試?
你輸了上下文this
。
getJasmineRequireObj().toThrowError = function(j$) {
function toThrowError () {
return {
compare: function(actual) {
var threw = false,
pass = {pass: true},
fail = {pass: false},
thrown;
if (typeof actual != 'function') {
throw new Error('Actual is not a Function');
}
var errorMatcher = getMatcher.apply(null, arguments);
try {
actual(); // call function reference component.someMethod
我會寫
expect(component.someMethod.bind(component)).toThrowError(CustomError);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.