在Create React App(TypeScript)中配置Mocha+Enzyme测试遇TS编译错误求助
Hey there! Let's get your Mocha + Enzyme setup working smoothly with your TypeScript Create React App, and squash those compilation errors you're facing. Here's a step-by-step breakdown:
1. Install All Required Dependencies
First, you'll need to add Mocha, Enzyme, and the necessary TypeScript type definitions + compilers. Run this in your project root:
npm install --save-dev mocha enzyme @types/mocha @types/enzyme @wojtekmaj/enzyme-adapter-react-17 ts-node tsconfig-paths @babel/preset-typescript @babel/preset-react
(Note: Swap @wojtekmaj/enzyme-adapter-react-17 with the version matching your React install—e.g., react-18 if you're on React 18.)
2. Update Your Test Script in package.json
Replace your existing test script with one that tells Mocha to use TypeScript via ts-node and respect your path aliases:
"scripts": { "test": "mocha -r ts-node/register -r tsconfig-paths/register -r ./src/setupTests.ts src/**/*.test.tsx" }
-r ts-node/register: Lets Mocha process TypeScript/TSX files directly-r tsconfig-paths/register: Honors path aliases from yourtsconfig.json-r ./src/setupTests.ts: Loads Enzyme's adapter configuration (we'll create this next)
3. Configure Enzyme Adapter
Create a src/setupTests.ts file to initialize Enzyme with the correct React adapter:
import { configure } from 'enzyme'; import Adapter from '@wojtekmaj/enzyme-adapter-react-17'; configure({ adapter: new Adapter() });
4. Tweak tsconfig.json for Compilation Fixes
Update your TypeScript config to resolve the two errors you mentioned:
Fix for "Parameter 'obj' implicitly has an 'any' type"
Ensure your tsconfig.json has these settings (if you haven't already):
{ "compilerOptions": { "jsx": "react-jsx", // Or "react" for older React versions "strict": true, "noImplicitAny": true, // Forces explicit types (better for TypeScript) "esModuleInterop": true, // Fixes default export type issues "moduleResolution": "node" }, "include": ["src/**/*"] // Makes sure test files are included in compilation }
If you still see implicit any errors, go to the specific line in your test code and add a type annotation. For example, if you have a utility function in your test:
// Before (error): function logObj(obj) { console.log(obj); } // After (fixed): function logObj(obj: Record<string, unknown>) { console.log(obj); }
Or for Enzyme wrappers, use generics to specify your component's props:
import App from './App'; type AppProps = {}; // Add your actual props here const wrapper = shallow<AppProps>(<App />);
Fix for "Property 'default' does not exist on type '{}'"
This almost always stems from TypeScript misinterpreting default exports. The esModuleInterop: true setting above should fix this, but double-check your imports:
- Correct:
import App from './App';(for default exports) - Incorrect:
import * as App from './App';(this treats default exports as part of a module object)
If you're importing a third-party library and still see this, you can add a type assertion temporarily:
import * as AdapterModule from '@wojtekmaj/enzyme-adapter-react-17'; const Adapter = AdapterModule.default as typeof AdapterModule;
5. Example Working Test File
Here's a simple test for your App component to verify everything works:
import React from 'react'; import { shallow } from 'enzyme'; import App from './App'; describe('App Component', () => { it('renders the main heading', () => { const wrapper = shallow(<App />); expect(wrapper.find('h1').text()).toBe('Welcome to React + TypeScript'); }); });
内容的提问来源于stack exchange,提问作者amit umrikar

