Jest测试报错TypeError: Line_vue_1.default不是构造函数求助
TypeError: Line_vue_1.default is not a constructor in Jest Tests for Vue Class Components Let's break down why this error is happening and how to fix it, based on your setup:
Root Cause
When testing a class that inherits from your custom LineBase (which extends Vue), Jest's module resolution or transpilation isn't correctly resolving the default export of your Line class. Your console.log(typeof Line) returning object confirms this—you're getting the module wrapper object instead of the actual constructor function.
Solutions to Try
1. Sync esModuleInterop Between TSConfig and Jest
Your tsconfig.json has esModuleInterop: true, but Jest might not be inheriting this setting. Add it to your Jest config to ensure consistent module handling:
Update your jest.config.js:
module.exports = { // ... existing config globals: { "ts-jest": { esModuleInterop: true, tsconfig: "./tsconfig.json" // Explicitly align with your TS config } }, // ... rest of config };
2. Adjust Import Syntax in Tests
If the above doesn't resolve the issue, your transpiled code might be wrapping the default export in a module object. Try accessing the constructor directly from the module:
// Replace this: import Line from '@/path/to/Line'; // With this: import * as LineModule from '@/path/to/Line'; const Line = LineModule.default; const instance = new Line(); // This should now work
3. Mirror Vue Alias in Jest
Your vue.config.js aliases vue to a specific node_modules path to avoid duplicate Vue instances. Mirror this in Jest to prevent context mismatches:
Add to your jest.config.js moduleNameMapper:
moduleNameMapper: { ...pathsToModuleNameMapper(compilerOptions.paths), "^vue$": "<rootDir>/node_modules/vue" // Match your app's Vue alias },
4. Verify Class File Setup
Double-check these details:
- Ensure
LineBaseandLineare saved as.tsfiles (not.vuesingle-file components)—your Jest transform for.vuefiles is meant for SFCs, not plain class files. - Confirm no conflicting exports exist in either class file (your code shows correct default exports, but typos can slip in).
5. Ensure Your Source Files Are Transpiled
Add your app's source directory to Jest's excluded ignore list to make sure your classes are transpiled:
Update transformIgnorePatterns in jest.config.js:
transformIgnorePatterns: [ "node_modules/(?!variables/.*)", "<rootDir>/node_modules/button-plugin-vue", "!ClientApp/**/*" // Don't ignore your app's source files ],
Test After Changes
After applying one or more of these fixes, re-run your Jest test. The new Line() call should now correctly instantiate your class without the constructor error.
内容的提问来源于stack exchange,提问作者Ulia Savi

