NativeScript Angular配置Karma+Jasmine测试遇编译及排除失效问题
Let's break down and fix the two main issues you're facing: excluded directories still being scanned, and those TypeScript compilation errors for ES6 built-ins like Promise, Set, etc.
1. Fixing Excluded Directories (node_modules/platforms) Not Being Ignored
Karma's exclude and karma-typescript's file handling need precise wildcard patterns to properly ignore nested files. Here's what to adjust in your karma.conf.js:
Update the Root Exclude Array
Replace your current exclude with wildcard patterns to match all files inside these directories:
exclude: [ 'node_modules/**/*', 'platforms/**/*' ],
Add Karma-Typescript Specific Exclude Config
Karma-typescript has its own file processing pipeline, so you need to explicitly tell it to ignore these directories too. Add this block inside your config.set():
karmaTypescriptConfig: { exclude: ['node_modules/**/*', 'platforms/**/*'], // We'll add compiler fixes here next },
2. Resolving TypeScript Compilation Errors (Promise, Set, Iterable not found)
These errors happen because your TypeScript compiler isn't loading the ES2015 type definitions needed for these built-ins. Let's fix that in the karmaTypescriptConfig we just added:
karmaTypescriptConfig: { exclude: ['node_modules/**/*', 'platforms/**/*'], compilerOptions: { // Include ES2015 libs to get definitions for Promise, Set, etc. lib: ["es2015", "dom"], target: "es5", // Compile to ES5 for browser compatibility module: "commonjs", // Match Karma's module system types: ["jasmine"] // Load Jasmine type definitions for test syntax }, // Optional: Enable built-in coverage reporting instead of separate preprocessor coverageOptions: { exclude: [ /\.spec\.ts$/, // Ignore test files from coverage /node_modules/ ] } },
Bonus: Fix the "All files matched..." Warning
Your current files array includes app/**/*.ts which already covers app/tests/*.ts, causing the duplicate match warning. Update your files to separate source and test files clearly:
files: [ // Source files: not loaded directly, but available for imports in tests { pattern: 'app/**/*.ts', included: false }, // Test files: loaded and executed by Karma { pattern: 'app/tests/**/*.ts', included: true } ],
Then adjust your preprocessors to match (you can remove the separate coverage preprocessor since karma-typescript handles it):
preprocessors: { 'app/**/*.ts': ['karma-typescript'], 'app/tests/**/*.ts': ['karma-typescript'] },
Final Check: Install Missing Type Definitions
If you still see Jasmine-related type errors, make sure you have the Jasmine types installed:
npm install @types/jasmine --save-dev
Putting It All Together
Your updated karma.conf.js should now properly ignore node_modules/platforms, resolve the TypeScript lib issues, and eliminate the file match warning.
内容的提问来源于stack exchange,提问作者Francis Batista

