Check out our Angular Book Series.

Angular Unit Testing: How do I Fix a Platform with a Different Configuration Has Been Created?

I've run into this one a few times. You're setting up Unit Testing of an Angular application and get an error like this:

Uncaught Error: A platform with a different configuration has been created. Please destroy it first.

It's frustrating and a but confusing. If you Google on that error you'll find a bunch of stuff, but no explicit solution.

You've probably set up a TestBed configuration environment as part of your unit testing, probably like this:


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

TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());

However, somewhere in the code, the non-testing modules have been loaded, probably like this:


import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

The error occurs because of the conflict between the platformBrowserDynamic() and the platformBrowserDynamicTesting(). Make sure that you exclude the source files the import and initialization of the non-test version of the library.

In your karma.conf.js file add an exclude property to the Karma configuration object, something like this:


exclude : "src/app/main.ts",

In my case, today, the error was related to a missing '/' in the excluded directory structure.

I hope this helps someone.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.