Search code examples
angulartypescriptunit-testingkarma-jasmineangular-test

Angular - Karma Testing - Failed: Cannot read property 'textContent' of null


I have one failure when I run 'ng test' on my Angular 6 app:

Failed: Cannot read property 'textContent' of null


Please see sample app... SampleApp


The problem appears to be with the app.component.spec.ts file. See error message below:

AppComponentTest > -> should render title in a h1 tag
Failed: Cannot read property 'textContent' of null
    at <Jasmine>
    at UserContext.eval (./src/app/app.component.spec.ts?:31:44)
    at ZoneDelegate.invoke (./node_modules/zone.js/dist/zone.js?:387:26)
    at AsyncTestZoneSpec.onInvoke (./node_modules/zone.js/dist/zone-testing.js?:712:39)
    at ProxyZoneSpec.onInvoke (./node_modules/zone.js/dist/zone-testing.js?:284:39)
    at ZoneDelegate.invoke (./node_modules/zone.js/dist/zone.js?:386:32)
    at Zone.runGuarded (./node_modules/zone.js/dist/zone.js?:150:47)
    at runInTestZone (./node_modules/zone.js/dist/zone-testing.js?:840:29)
    at UserContext.eval (./node_modules/zone.js/dist/zone-testing.js?:774:17)
    at ZoneDelegate.invoke (./node_modules/zone.js/dist/zone.js?:387:26)
    at ProxyZoneSpec.onInvoke (./node_modules/zone.js/dist/zone-testing.js?:287:39)


Solution

  • The setup for the component under test includes CUSTOM_ELEMENTS_SCHEMA, which allows the use of custom tag elements in the template without complicating the test by instantiating the associated component. As a result, testing for an element in a child component from the parent fails. The solution is to move the failing test spec into proper child component.