You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cypress组件测试中RTK Query `api`出现初始化前访问错误的解决求助

Cypress组件测试中RTK Query api出现初始化前访问错误的解决求助

我在运行Cypress组件测试时遇到了这个错误:

The following error originated from your test code, not from Cypress.

Cannot access 'api' before initialization

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.

这个错误来自我的Redux Store配置文件store/index.ts:

import { configureStore } from '@reduxjs/toolkit';
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import { api } from './api/api';
import { sendErrorToSentryMiddleware } from './middlewares/sentry';
import { unauthenticateMiddleware } from './middlewares/unauthenticate';
import { debugReducer } from './reducers/debug';
import { loginPageErrorsReducer } from './reducers/errorMessages/loginPageErrors';
import { securityPageErrorsReducer } from './reducers/errorMessages/securityPageErrors';
import { profileReducer } from './reducers/profile';
import { reauthReducer } from './reducers/reauth/reauth';
import { shareReservationReducer } from './reducers/sharereservation';

const store = configureStore({
    reducer: {
        profile: profileReducer,
        securityPageErrors: securityPageErrorsReducer,
        loginPageErrors: loginPageErrorsReducer,
        reauth: reauthReducer,
        shareReservation: shareReservationReducer,
        debug: debugReducer,
        [api.reducerPath]: api.reducer, // 触发错误的行
    },
    preloadedState: {},
    middleware: getDefaultMiddleware =>
        getDefaultMiddleware().concat([
            api.middleware,
            unauthenticateMiddleware,
            sendErrorToSentryMiddleware,
        ]),
    enhancers: getDefaultEnhancers => {
        return getDefaultEnhancers().concat(sentryReduxEnhancer);
    },
});

看起来Cypress会复制整个项目代码库来运行测试,但我的组件测试根本不需要用到Redux Store,有没有办法解决这个问题?

我试过在组件测试文件里手动添加Redux Store,但没用:

import { configureStore } from '@reduxjs/toolkit';
import { mount } from 'cypress/react';
import React from 'react';
import { Provider } from 'react-redux';
import SellCalculator from '../../src/components/pages/funds/SellCalculator';
import { ModalContext } from '../../src/context/modalContext';
import { api } from '../../src/store/api/api';

describe('SellCalculator', () => {
    const defaultProps = {
        sharePrice: 100,
        totalShares: 15,
        onChange: cy.stub().as('onChangeSpy'),
    };

    const store = configureStore({
        reducer: {
            [api.reducerPath]: api.reducer,
        },
        middleware: getDefaultMiddleware =>
            getDefaultMiddleware({
                serializableCheck: false,
            }),
    });

    const mountWithContext = (props = defaultProps) => {
        const setModal = cy.stub().as('setModalSpy');

        mount(
            <Provider store={store}>
                <ModalContext.Provider
                    value={{
                        setModal,
                        Modal: null,
                        loading: false,
                        setLoading: () => {},
                    }}
                >
                    <SellCalculator {...props} />
                </ModalContext.Provider>
            </Provider>
        );
    };

    it('renders with initial values', () => {
        mountWithContext();

        cy.contains('Share price (USD)').should('be.visible');
        cy.contains('$100').should('be.visible');
        cy.contains('Sell price (USD)').should('be.visible');
        cy.contains('$100').should('be.visible'); // Initial value is 1 share
    });
});

有没有解决办法?理想情况下我希望Cypress只使用被测试组件相关的文件。

备注:内容来源于stack exchange,提问作者João Pedro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 09:53:03