Angular7中ng test无法显示代码构建错误的问题求助
ng test Show Build Errors in Console Instead of Timing Out I've run into this exact frustrating issue before—when your code has build errors (like duplicate imports), ng serve calls out the problem immediately, but ng test just hangs waiting for Chrome to connect until it times out, leaving you totally in the dark about what's broken. Here's how to fix it:
Why This Happens
By default, ng test runs in watch mode (--watch=true), and Angular CLI's test build pipeline fails to surface initial build errors to the console in this mode. Instead, it gets stuck in a failed build state, never progressing to start Karma properly, which causes the browser timeout you're seeing. The good news is there are a few straightforward fixes.
Fix 1: Run Tests Without Watch Mode (Quickest Win)
As you noticed, adding --watch=false to your test command forces a one-time build and test run. This will immediately dump any build errors (like your duplicate import) to the console instead of hanging:
ng test --watch=false
This is perfect for quick sanity checks or CI pipelines where you don't need watch mode.
Fix 2: Force Verbose Logging in Test Configuration
If you prefer to keep watch mode enabled but still want to see initial build errors, tweak your Angular project's configuration to force verbose logging for test builds:
- Open your
angular.jsonfile in the root of your project. - Navigate to
projects -> [your-project-name] -> architect -> test -> options. - Add a
"verbose": trueentry to the options object. Your test config should look something like this:
"test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "src/test.ts", "polyfills": "src/polyfills.ts", "tsConfig": "src/tsconfig.spec.json", "karmaConfig": "src/karma.conf.js", "assets": ["src/favicon.ico", "src/assets"], "styles": ["src/styles.scss"], "scripts": [], "verbose": true } }
With this change, the test build will log all details to the console, including initial build errors, before attempting to start Karma.
Fix 3: Pre-Build Test Code to Catch Errors First
If you want to isolate the build step entirely, run a test-specific build first. This will surface any errors immediately without touching Karma:
ng build --target=test
Once the build succeeds, you can run ng test normally without worrying about hidden build issues causing timeouts.
Bonus: Watch Mode Quirk
As you noted, once watch mode is running and you modify a file, the rebuild will show errors. The problem only affects the initial build in watch mode. The fixes above address that initial blind spot.
内容的提问来源于stack exchange,提问作者Johan Aspeling

