Angular TestBed fails with Webpack, Karma/Jasmine
Asked Answered
Q

1

6

I tried to use Angular TestBed as described on angular.io website to test a simple component, but I get errors like: TypeError: undefined is not an object (evaluating 'ProxyZoneSpec.assertPresent') and 404 as it cannot load the external component template.

If I create a sample unit test, without using/setting up TestBed, it works correctly, therefore at least Karma and Jasmine are set up correctly for the project. The problem is related to Angular TestBed. Is there any other documentation than angular.io? as following those docs it does not seem to work.

karma.conf.js

var webpackConfig = require('./webpack/webpack.dev.js');

module.exports = function (config) {
  config.set({
      basePath: '',
      frameworks: ['jasmine'],
      files: [            
        './app/polyfills.ts',
        './app/**/*.spec.ts',
      ],
      exclude: [    ],
      preprocessors: {
        './app/polyfills.ts': ['webpack', 'sourcemap'],
        './app/**/*.spec.ts': ['webpack', 'sourcemap']
      },
      webpack: {
        devtool: 'inline-source-map',
        module: webpackConfig.module,
        resolve: webpackConfig.resolve
      },
      mime: {
        'text/x-typescript': ['ts', 'tsx']
      },

reporters: ['progress', 'junit', 'tfs'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false,
concurrency: Infinity
})
}

component.ts

import { Input, Component } from "@angular/core";

@Component({
    selector: "user-contact",
    templateUrl: "./user-contact.component.html",
    styleUrls: ["./userContact.scss"],
})

export class UserContactComponent {

    @Input()
    public name: string;
}

component.spec.ts

 import { ComponentFixture, TestBed, async } from "@angular/core/testing";
 import {
     BrowserDynamicTestingModule,
     platformBrowserDynamicTesting,
 } from "@angular/platform-browser-dynamic/testing";
 import { By } from "@angular/platform-browser";
 import { DebugElement } from "@angular/core";

 import { UserContactComponent } from "./user-contact.component";

 // zone.js
  import "zone.js/dist/proxy";
  import "zone.js/dist/sync-test";
  import "zone.js/dist/async-test";

  // Without this import I get the following error:
  // Expected to be running in 'ProxyZone', but it was not found
  import "zone.js/dist/jasmine-patch"; 

  TestBed.initTestEnvironment(
      BrowserDynamicTestingModule,
      platformBrowserDynamicTesting(),
  );

  describe("Component: user contact", () => {

  let component: UserContactComponent;
  let fixture: ComponentFixture<UserContactComponent>;

    beforeEach(async(() => {
      TestBed.configureTestingModule({
          declarations: [UserContactComponent],
      })
    .compileComponents();
    }));

    it("should have a defined component", () => {
       fixture = TestBed.createComponent(UserContactComponent);
       component = fixture.componentInstance;
       fixture.detectChanges();
       expect(this.component).toBeDefined();
    });
  })
Queenqueena answered 28/8, 2017 at 11:57 Comment(4)
did you try removing the part calling initTestEnvironment() ?Acroter
Did you see about this old angular issue ? Maybe this is linked : github.com/angular/angular/issues/11317Acroter
I had similar issue and moving angular imports below zone imports helped.Charity
@ BartBiczBoży: I re-arranged the imports and indeed it worked. If you create an answer from your comment, I will accept it. Thanks.Queenqueena
B
5

@BartBiczBozy, your answer "I had similar issue and moving angular imports below zone imports helped." fixed my issue. I have been struggling with this all day! Thank you!

To others searching for answers, my test.ts looks like this now

import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';

import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

I did not end up having to make any changes to my karma.conf.js files array. It only contains my spec files pattern.

Boyar answered 31/7, 2018 at 20:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.