使用Jest+React Testing Library测试StencilJS React包装组件遇阻
配置React Testing Library测试StencilJS React包装组件的问题
问题描述
在配置React Testing Library测试StencilJS生成的React包装组件时,运行测试抛出以下错误:
Test suite failed to run TypeError: Cannot read properties of undefined (reading 'Component') 31 | 32 | const displayName = dashToPascalCase(tagName); > 33 | const ReactComponent = class extends React.Component<StencilReactInternalProps<ElementType>> { | ^ 34 | componentEl!: ElementType; 35 | 36 | setComponentElRef = (element: ElementType) => {
推测问题与defineCustomElements的调用有关,已尝试将如下代码添加到Jest setup脚本、beforeAll函数以及测试文件顶部,但问题未解决:
import { defineCustomElements } from '@salable/stencil-library/loader'; defineCustomElements(window);
当前测试文件代码:
import React from 'react'; import { render, screen } from '@testing-library/react'; import {MyComponent} from "../lib"; import '@testing-library/jest-dom'; import { waitFor } from '@testing-library/react'; import { defineCustomElements } from '@salable/stencil-library/loader'; defineCustomElements(window); test('component loads and renders', async () => { render(<MyComponent />); await waitFor(() => { expect(screen.getByText(/hello/i)).toBeInTheDocument(); }); });
jest.config.js配置:
module.exports = { transform: { '^.+\\.(ts|tsx)$': ['ts-jest', { tsconfig: 'tsconfig.test.json', }], }, moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], testPathIgnorePatterns: ['/node_modules/', '/dist/'], setupFilesAfterEnv: ['@testing-library/jest-dom', '<rootDir>/__tests__/jest.setup.ts'], testEnvironment: 'jsdom', clearMocks: true, };
解决方法
全局挂载React实例
错误提示React.Component未定义,说明Stencil生成的包装组件未正确获取到React。在Jest全局setup文件(jest.setup.ts)中添加:import React from 'react'; global.React = React;异步执行自定义元素注册
将defineCustomElements放在beforeAll中异步调用,确保注册完成后再执行测试:// 测试文件内 import { defineCustomElements } from '@salable/stencil-library/loader'; beforeAll(async () => { await defineCustomElements(window); });检查测试用TypeScript配置
确保tsconfig.test.json包含React相关配置:{ "extends": "./tsconfig.json", "compilerOptions": { "jsx": "react-jsx", "types": ["jest", "@testing-library/jest-dom"] } }Mock Stencil loader依赖
若上述方法无效,可尝试mock loader模块:jest.mock('@salable/stencil-library/loader', () => ({ defineCustomElements: jest.fn().mockResolvedValue(true) }));
内容的提问来源于stack exchange,提问作者OrderAndChaos
相关产品推荐
相关产品推荐

