Framework7+React Context组件Jest单元测试报错:Cannot read 'emit'
Framework7 + React Context单元测试报错:TypeError: Cannot read properties of undefined (reading 'emit')
我正在为采用Framework7、React Context与useReducer架构的应用编写单元测试,目标是Mock Context数据,测试Context值变更后组件的更新逻辑。目前已解决Context Provider的测试问题,但测试组件本身时触发错误:
TypeError: Cannot read properties of undefined (reading 'emit') at Framework7.emit
以下是我的jest.config.js配置:
const esModules = ['framework7', 'framework7-react', 'framework7-icons', 'framework7-react', 'react-dom'].join('|') module.exports = { preset: 'ts-jest', transform: { '^.+\\.(ts|tsx)?$': 'ts-jest', "^.+\\.(js|jsx)$": "babel-jest", }, moduleFileExtensions: [ "js", "json", "jsx", "ts", "tsx", ], testPathIgnorePatterns: [ "/node_modules/(?!(framework7))" ], transformIgnorePatterns: [`<rootDir>/node_modules/(?!(${esModules})/)`], "testEnvironment": "jsdom", moduleNameMapper: { '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/assetsTransformer.js', '\\.(css|less)$': '<rootDir>/assetsTransformer.js', }, };
以及测试代码:
import { Framework7Parameters } from "framework7/types"; import routes from "../../routes" import App from "../../components/App" import { renderHook, act } from '@testing-library/react-hooks'; const f7params: Framework7Parameters = { id: "io.framework7.testapp", // App bundle ID name: "Test", // App name theme: "auto", // Automatic theme detection // App routes routes, }; jest.mock("socket.io-client", () => { const emit = jest.fn(); const on = jest.fn(); const socket = { emit, on }; return jest.fn(() => socket); }); const state: iState = { test: "some test", user: "testUser" } const dispatch = jest.fn(); const wrapper: React.FC = ({ children }) => ( <StateContext.Provider value={{ state, dispatch }}> <App /> {/* <- 必须添加App,否则Framework7 App参数对组件无效 */} </StateContext.Provider> ); const mockUseContext = jest.fn().mockImplementation(() => ({ state, dispatch })); React.useContext = mockUseContext; describe('Component test', () => { test('rendering HomePage', () => { const { result } = renderHook(() => HomePage(f7params), { wrapper }); // act(() => { // result.current.testFunction() // 甚至无法执行组件内的函数 // }) expect(screen.getByText(/testUser/i)).toBeInTheDocument(); }); });
内容的提问来源于stack exchange,提问作者Ilimkan Omurzakova
相关产品推荐
相关产品推荐

