How do I import and compile html files into the Jasmine unit tests using Angular 10?

  angular, jasmine, karma-jasmine, webpack

Been stuck on this for a few days and so far nothing I have tried seems to work.

We have a large Angular 10 project that uses a library of Angular components.

Inside of the same mono repo I have another Angular project which consumes those library components.

Directory / Project

  /projects
    /my-front-and-app
      /src/
        /app/
          app.component.html
          app.component.ts
          app.component.spec.ts
          app.component.scss
    /library-components
       /src/
         /lib/
           /header/
           /footer/
           /sidenav/
             sidenav.component.html
             sidenav.component.ts
             sidenav.component.spec.ts
             sidenav.component.scss

Okay so the front end component just consumes all the library components

app.component.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <base href="/" />
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>{{ title }}</title>
  </head>
  <body>
    <lib-header></lib-header>

    <div class="container-fluid">
      <div class="row">
        <div class="sidebar">
          <lib-sidebar-nav> </lib-sidebar>
        </div>

        <div class="col">
          <div class="my-container">
            <div>
              <router-outlet></router-outlet>
              <hr />
            </div>
          </div>
        </div>
      </div>
    </div>

    <lib-footer></lib-footer>
  </body>
</html>

So the problem is when I try test my front end component (app.component.ts) which cosumnes those components it fails because it can’t seem to find their template.

So here’s my unit test.

app.component.spec.ts


import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { DebugElement } from '@angular/core';

import {
  HeaderComponent,
  FooterComponent,
  SidebarNavComponent,
} from 'lib-platform-components';

import { AppComponent } from './app.component';

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let el: DebugElement;

  beforeEach( waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [
          AppComponent,
          HeaderComponent,
          SideNavComponent,
          FooterComponent
        ],
        imports: [
          RouterTestingModule,
          HttpClientTestingModule
        ], 
      })
        .compileComponents()
       
    })
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    el = fixture.debugElement;

    fixture.detectChanges();
  });

  it('should create the app', () => {
    expect(component).toBeTruthy();
  });

});

Basically what I get is the the same error.

Error: This test module uses the component HeaderComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test.

So I’ve tried a couple of things. Including the one recommended by Angular’s docs. overrideComponent but I wouldn’t be here if that worked

        .overrideComponent(SideNavComponent, {
          set: {
            templateUrl: '../../../library-components/src/lib/sidenav/sidenav.component.html',
            styleUrls: ['../../../library-components/src/lib/sidenav/sidenav.component.scss']
          }
        })

Give me same error

Failed: Uncaught (in promise): Failed to load ../../../lib-platform-components/src/lib/header/header.component.html

So I’m out of ideas. I’m guessing this is some sort of Webpack / Karma config thing but I’ve had little luck there as well.

Here’s my karam.conf

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma'),
    ],
    client: {
      clearContext: false, // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../../coverage/app'),
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true,
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    restartOnFileChange: true,
    proxies: {
      '/assets/fonts/': '../kds-assets/fonts/',
      '/assets/icons/': '../kds-assets/icons/',
      '/assets/images/': '../kds-assets/images/',
    },
  });
};

Anyhow, any help is appreciated at this point.

Thanks

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.