I am following this tutorial: https://angular.io/guide/testing#component-test-scenarios for karma+jasmine unit testing. Here my code:
import { AppComponent } from "./app.component";
import { ComponentFixture, TestBed } from "@angular/core/testing";
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let h1: HTMLElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent ],
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
h1 = fixture.nativeElement.querySelector('h1');
});
it('should display original title', () => {
expect(h1.textContent).toContain("Ciao");
});
});
When I run the test I get the following exception:
TypeError: Cannot read property 'getComponentFromError' of null
at TestBed._initIfNeeded (D:/Users/apwzp/AppData/Local/Temp/karma-typescript-bundle-11944DDd01l2f5Y0P.js:1020:52)
at TestBed.createComponent (D:/Users/apwzp/AppData/Local/Temp/karma-typescript-bundle-11944DDd01l2f5Y0P.js:1174:14)
at Function.TestBed.createComponent (D:/Users/apwzp/AppData/Local/Temp/karma-typescript-bundle-11944DDd01l2f5Y0P.js:876:29)
at UserContext.<anonymous> (assets/app/app.component.spec.ts:14:20 <- assets/app/app.component.spec.js:13:37)
at ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:388:26)
at ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:79:39)
at ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:387:32)
at Zone.run (node_modules/zone.js/dist/zone.js:138:43)
at UserContext.<anonymous> (node_modules/zone.js/dist/jasmine-patch.js:106:34)
Does anyone know how to solve it?
TestBed.initTestEnvironment()
in a different file and made sure that file is loaded before myspec.ts
files. Why does moving the init code to the.spec.ts
file fix this error? – Anikaanil