Jest测试Email输入组件报错:React.createElement类型无效问题排查
Hey there! That error you're hitting is super common when dealing with React component imports/exports in tests—let's walk through exactly how to fix it.
First, let's recap the error to make sure we're on the same page:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
As the warning hints, this almost always means your test can't properly access the Login component because of a mismatch between how you exported it and how you imported it, or a missing export entirely.
Here are the most likely fixes to check:
1. Match Export/Import Styles
React has two main export types, and mixing them up will result in an undefined component:
- Default Export: If your
Logincomponent usesexport default Login(either for a class or function component), your test must use a default import:// In Login.js (component file) export default function Login() { /* ... */ } // In your test file import Login from './Login'; // No curly braces! - Named Export: If you used a named export like
export function Login() { ... }, your test needs to use curly braces for the import:// In Login.js export function Login() { /* ... */ } // In your test file import { Login } from './Login'; // Curly braces required!
2. Verify the Component Actually Exists in Its File
Double-check your Login component file to make sure you didn't forget the export statement entirely. It's easy to write the component logic but skip adding export at the top!
For example, this will cause the error:
// Oops—no export here! function Login() { // Component code }
Fix it by adding the appropriate export (default or named).
3. Check Your Import Path
A typo in the import path can also lead to importing an empty/undefined module. Make sure the relative path to your Login component is correct in the test file.
For example, if your test is in src/tests/Login.test.js and the component is in src/components/Login.js, your import should be:
import Login from '../components/Login';
A wrong path like ./components/Login would point to a non-existent file, resulting in an undefined import.
4. Check for Typos in Component Name
Even a small typo (like LogIn instead of Login) will cause React to look for a component that doesn't exist, resulting in the same error. Double-check the component name in both the export and import, and when you render it in the test:
// Wrong—typo in component name render(<LogIn />); // Correct render(<Login />);
Once you fix the import/export issue, your test should be able to render the Login component properly, and you can verify the email input's change event behavior as expected.
内容的提问来源于stack exchange,提问作者Carlos Vieira

