You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular7中ng test无法显示代码构建错误的问题求助

Angular 7: Make 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:

  1. Open your angular.json file in the root of your project.
  2. Navigate to projects -> [your-project-name] -> architect -> test -> options.
  3. Add a "verbose": true entry 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:22:06