Categories
Angular Tutorials

Fix Angular Error: Cannot set base providers because it has already been called

Those of you who are getting into angular testing, normally face this error. Usually this happen when we set the testing environment for Angular. These are the lines

These are the culprits

TestBed.initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
) 
// or wrapped in beforeAll 
beforeAll(() {
  TestBed.initTestEnvironment(
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting()
  )
})

Diagnosing & Solution

I might not have written this post if the error message was easy to understand

Your test might run just fine, even if this error occurs. All it says that above lines ran twice in your codebase.

Just look at the tests.ts file

tests.js file generated by angular cli technbuzz.com

Now let’s see the actual content of test.tsI really don’t know whether this configuration came from the beginning. Or were they added in recent angular version i-e version 6

tests file generated by angular cli for karma test runner technbuzz.com

So next time don’t include them in your jasmine beforeEach block of your spec files

4 replies on “Fix Angular Error: Cannot set base providers because it has already been called”

i followed the same steps as you said and it resolves one issue but there is another problem when implementing that code is, it reduces the percentage of code coverage. it totally ignores the test cases. then how should i solve these two problems.

Thanks for commenting. It’s been quite a while since I wrote this code, if time permits I will update it.

Leave a Reply

Your email address will not be published. Required fields are marked *

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