Angular 6 with Jest unit testing

758 views Asked by At

I cloned a starter project using Angular 6 (https://github.com/KrunalLathiya/Angular6CRUDTutorial). I removed Karma and installed Jest instead. The site loads fine, but the unit test fails with this error:

Illegal state: Could not load the summary for directive AppComponent.
  at syntaxError (../../../../../execroot/angular/packages/compiler/src/util.ts:100:17)
  at CompileMetadataResolver.Object.<anonymous>.CompileMetadataResolver.getDirectiveSummary (../../../../../execroot/angular/packages/compiler/src/metadata_resolver.ts:426:11)...

app.component.ts:

import { Component } from '@angular/core';
import { SlimLoadingBarService } from 'ng2-slim-loading-bar';
import { 
  NavigationCancel,
  Event,
  NavigationEnd,
  NavigationError,
  NavigationStart,
  Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app';
  constructor(private _loadingBar: SlimLoadingBarService, private _router: Router) {
    this._router.events.subscribe((event: Event) => {
      this.navigationInterceptor(event);
    });
  }
  private navigationInterceptor(event: Event): void {
    if (event instanceof NavigationStart) {
      this._loadingBar.start();
    }
    if (event instanceof NavigationEnd) {
      this._loadingBar.complete();
    }
    if (event instanceof NavigationCancel) {
      this._loadingBar.stop();
    }
    if (event instanceof NavigationError) {
      this._loadingBar.stop();
    }
  }
}

app.component.test.ts:

import { AppModule } from "./app.module";
import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { APP_BASE_HREF } from '@angular/common';
import { Router } from '@angular/router';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
  beforeEach(() => {
    class loading = { return { events: {} } };
    class router = {};
    TestBed.configureTestingModule({
      // imports: [AppModule], // didn't help
      declarations: [
        AppComponent
      ],
      providers: [
        AppComponent,
        // { provide: APP_BASE_HREF, useValue: '/' }, // didn't help
        { provide: SlimLoadingBarService, useClass: loading },
        { provide: Router, useClass: router }
      ],
    }).compileComponents();
  });

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
  });
});

Do I need something specific for Jest and Angular to work together? Thanks!

0

There are 0 answers