Test generated by angular CLI fails if in a specific folder

4.6k views Asked by At

I've generated a component in my components folder using the angular CLI (v6.1.4) by running ng g c components/foo and have then run ng test. The test for the new component fails with the following errors:

Zone is needed for the async() test helper but could not be found. Please make sure that your environment includes zone.js/dist/zone.js thrown

Error: Illegal state: Could not load the summary for directive FooComponent.

Oddly, if I run ng g c foo (i.e. so it's not generated in the components folder), the test then passes. My tests are all working for other folders, but this is the first test in my components folder (and is also the first test for a component). None of the other tests are asynchronous.

I'm fairly new to ng test so I might be missing something very obvious. I wasn't expecting to need to set up anything with zone.js for the default test to run. Where should I configure this? Or is there something else I'm missing here, perhaps something specific to my components folder?

3

There are 3 answers

0
Tim On BEST ANSWER

Adding the following to the top of foo.component.spec.ts fixed the issue, but I still don't understand why the tests worked if they weren't in the components folder. If someone has an explanation, or a solution that doesn't involve repeating this in every component's test file, I'd love to hear it!

import 'zone.js';
import 'zone.js/dist/async-test.js';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
0
Santironhacker On

In adition to @BrunoJCM comment above which solved my issue by organizing the imports on test.ts file, bear in mind the following settings in your project might make you run into the problem again, so concerning the test.ts file, check the following:

  1. Deactivate onSave optimize imports.
  2. Avoid running Prettier, Beautify or other code style formatter that reorganizes the imports (either package or plugin).
  3. Check for pre-commits hooks like Husky that formats the files and reorganize the imports.

Enjoy hassle-free coding! :D

3
Bruno Medeiros On

In my case here, I wondered if my project might have been generated with a different version of the main test configuration, so I created a new empty project with Angular CLI, compared both versions of src/test.ts and I realised that this file was indeed different, my app was missing the following line as the first one:

import 'zone.js/dist/zone-testing'

After adding it to the src/test.ts file, this error was gone!

This is probably way better than importing all those js files to all specs as Tim's answer suggests.