Angular如何运行单个/一组单元测试?测试无结果问题求助
Hey there! Let’s troubleshoot why your test setup isn’t detecting your Home component specs and cover reliable ways to run single or groups of tests.
First: Fix the require.context Not Working Issue
Your current code in src/test.ts might be failing because of an incorrect path or regex pattern. Let’s adjust that:
1. Correct the Relative Path
Since your test.ts lives in the src directory, and your Home component’s test is in app/pages/home, you need to fix the relative path in require.context:
// If your test file is app/pages/home/home.spec.ts const context = require.context('../app/pages/home', false, /\.spec\.ts$/); context.keys().forEach(context);
- The first argument
../app/pages/homepoints directly to the directory where your test file lives (relative tosrc/test.ts). - Using
falsefor the second argument means we don’t need to recursively search subdirectories here (since your test is in the target folder itself).
2. Fix the Regex Pattern
Your original regex /\home\.spec\.ts$/ has an unnecessary escape before h (alphabetic characters don’t need escaping in regex). A cleaner pattern would be /home\.spec\.ts$/ if you want to specifically match this file, or /\.spec\.ts$/ to match all test files in that directory.
Alternative Ways to Run Single/Group Tests
If you want a more straightforward approach (without relying on require.context), most test frameworks (like Jest, Vitest, etc.) let you specify test files directly via the command line:
Run a Single Test File
# For Jest/Vitest (adjust the script name if your package.json uses "test:unit" instead) npm test -- app/pages/home/home.spec.ts
Run a Group of Tests
To run all tests under the pages directory:
npm test -- app/pages/**/*.spec.ts
The ** wildcard matches all subdirectories, so this will pick up every .spec.ts file in app/pages and its subfolders.
Double-Check Your Test Framework Configuration
Make sure your test framework isn’t ignoring your test files:
- For Jest: Check your
jest.config.jsfile’stestMatchortestPathIgnorePatternssettings. Ensureapp/pages/**/*.spec.tsisn’t excluded. - For Vitest: Verify the
includearray invitest.config.tsincludes your test file paths, like['app/**/*.spec.ts'].
内容的提问来源于stack exchange,提问作者Whisher

