Apollo MockedProvider抛出‘Element type is invalid’错误求助
React Apollo useQuery组件测试报错:React.createElement类型无效
console.error node_modules/react/cjs/react.development.js:209
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
测试代码
import { MockedProvider } from '@apollo/client/testing' import React from 'react' import { render } from '@testing-library/react' import { customerList } from '../../mocks' import { ListCustomers } from '../../queries' import CustomerListContainer from '../CustomerListContainer' import '@testing-library/jest-dom' const mocks = [ { request: { query: ListCustomers, }, result: { data: customerList, }, }, ] describe('components: <CustomerListContainer />', () => { it('renders customer list', () => { render( <MockedProvider mocks={mocks} addTypename={false}> <CustomerListContainer customerRole="ADMIN" /> </MockedProvider> ) }) })
组件代码
import React from 'react' import { useQuery } from '@apollo/client' import { CustomerList } from '../components' import { ListCustomers } from '../queries' const CustomerListContainer = ({ customerRole }: { customerRole: string }) => { const { data, loading, error } = useQuery(ListCustomers, { variables: { filter: { role: { eq: customerRole, }, }, }, }) if (error) return <h1>Something went wrong.</h1> if (loading) return <h1>Loading...</h1> return ( <CustomerList customers={data.listCustomers.items} /> ) } export default CustomerListContainer
依赖版本
"@apollo/client": "^3.7.1", "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "react": "^18.2.0", "react-dom": "^18.2.0",
补充说明:项目基于Create React App创建。
问题排查与修复
这个错误的核心是React尝试渲染的组件类型为undefined,结合代码来看,大概率是CustomerList组件的导入方式错误:
修正
CustomerList导入方式- 如果
CustomerList组件是默认导出(即文件中是export default CustomerList),则需要改为默认导入:
若import CustomerList from '../components/CustomerList'../components是索引文件,需确保索引文件中是命名导出CustomerList,否则依然会出现导入为undefined的情况。
- 如果
验证查询导入有效性
- 同时确认
ListCustomers查询的导出/导入是否匹配,确保它是一个有效的GraphQL查询文档。
- 同时确认
完善测试的异步逻辑
- 当前测试未等待查询完成就结束,即使修复组件导入,也可能无法验证渲染结果。建议添加异步等待逻辑:
it('renders customer list', async () => { const { findByText } = render( <MockedProvider mocks={mocks} addTypename={false}> <CustomerListContainer customerRole="ADMIN" /> </MockedProvider> ) // 等待加载状态消失,或等待mock数据中的客户名称出现 await findByText('Loading...') const targetCustomer = await findByText('你的mock数据中的客户名') expect(targetCustomer).toBeInTheDocument() })
- 当前测试未等待查询完成就结束,即使修复组件导入,也可能无法验证渲染结果。建议添加异步等待逻辑:
内容的提问来源于stack exchange,提问作者xeno9
相关产品推荐
相关产品推荐

