redux 无法读取未定义的属性(阅读“injectEndpoints”)

xmakbtuz  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(177)

我最近将我的项目从Create React App迁移到Vite,随后决定将我的测试框架切换到Vitest,同时保留React测试库用于我的测试。迁移后,我遇到了一个问题,我的测试失败,因为我对我的RTK查询端点进行了重组。最初,我的所有端点都位于一个文件中,但为了更好的可读性和维护性,我决定使用injectEndpoints将它们拆分。但是,此更改导致测试失败,并显示错误消息:“无法读取未定义的属性(阅读”injectEndpoints“)"。
在我的测试中,为了模拟端点,我使用了Mock Service Worker(MSW)。在端点迁移和重组之前,一切都按预期运行。现在,我不知道如何解决这个问题,让我的测试再次通过新的设置。下面是我如何构建端点和相关配置的版本:
测试

describe('Wall of experts', () => {
const user = {
    "givenName": "XXXX",
    "familyName": "XXXXX",
    "name": "XXXXX",
    "departmentnumber": "XXX",
    "email": "XXXXXXXXXXXX",
    "sub": "XXXXX",
    "authorities": ["XXXX", 'XX']
}

beforeAll(() => {
    initI18nMock({})
    add18nResourcesMock({
        "maintenance": {
            "infoTexts": {
                "user-email-address": "User email",
            }
        },
        "expertWall": {
            "infoTexts": {
                "success-update-message": "User has been successful updated",
                "success-remove-message": "User has been successful deleted",
                "success-add-message": "User has been successful added"
            }
        }
    })

    server.listen()
    store.dispatch(setLoggedUser(user))
})

afterEach(() => {
    // Cleanup
    add18nResourcesMock({})
    server.resetHandlers()
})

afterAll(() => {
    server.close()
})

it('should display wall of experts', async () => {
    customRender(<><AppSnackbar/><ExpertWall/></>)

    await screen.findAllByTestId('user')

    const displayedUsers = screen.queryAllByTestId('user')

    // Check rendered users amount against mocked data.
    expect(displayedUsers).toHaveLength(mockWallOfExperts.length)

})

配置test-utils,以便能够在vite中运行react测试库。

afterEach(() => {
    cleanup()
})

const AllTheProviders = ({ children }: {children: React.ReactElement}) => {
    return (
        <BrowserRouter basename={'/'}>
            <Provider store={store}>{children}</Provider>
        </BrowserRouter>
    );
};

function customRender(ui: React.ReactElement, options= {})  {
    return render(ui, { wrapper: AllTheProviders, ...options });
}

export * from '@testing-library/react'
export { default as userEvent } from '@testing-library/user-event'
// override render export
export { customRender as render }

一家商店

const store = configureStore({
    reducer: {
        [datenlandkarteApi.reducerPath]: datenlandkarteApi.reducer,
        [cloudBMWApi.reducerPath]: cloudBMWApi.reducer,
        datenTicket: datenTicketReducer,
        dataRequestWizard: dataRequestWizardReducer,
        main: mainReducer,
    },
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware().concat(datenlandkarteApi.middleware, cloudBMWApi.middleware),
});
export type RootState = ReturnType<typeof store.getState>;

export type AppDispatch = typeof store.dispatch;

export default store;

这里是一个主文件,其中所有的端点,我只是过去beggining它。

export const apiName = createApi({
    reducerPath: 'apiName ',
    baseQuery: fetchBaseQuery({
        mode: 'cors',
        baseUrl: `${baseUrl}/api/`,
        prepareHeaders: (headers) => {
            const token = getAccessToken();
            if (token) {
                headers.set('Authorization', `Bearer ${token}`);
                // headers.set('Accept', `application/json`);
            }
            return headers;
        },
    }),
    tagTypes: rtkTagTypesValues,
    endpoints: (build) => ({
        // GETTERS i.e. RTK query
        getPerson: build.query<api.PersonDTO, string>({
            query: (email) => ({
                url: `person/getByEmail/${email}`,
                responseHandler: mapToJson,
            }),
        }),

这是我的injectedEndpoints

const useCasePurposeApi = datenlandkarteApi.injectEndpoints({
    endpoints: (build) => ({
        getUseCasePurposes: build.query<UseCasePurposesShortDto, GetUseCasePurposesRequestDto>({
            query: ({ useCaseRef, pageNumber = 0, pageSize = 5 }) => {
                return {
                    url: `sec/use-case-purposes/${useCaseRef}/short?pageNumber=${pageNumber}&pageSize=${pageSize}`,
                };
            },
            providesTags: (result) => {
                if (result) {
                    return [RtkTagTypes.ALL_PRIVACY_PURPOSE];
                }
                return [];
            },
        }),

我已经遵循了Vite和Vitest的文档和示例,并查看了有关injectEndpoints的RTK Query文档,但我无法查明此错误的原因。如果您对如何解决此问题以及如何在新配置下成功运行测试有任何见解或建议,我将不胜感激。谢谢你,谢谢!
其他想法:这个问题可能与RTK查询有关,也许需要以某种方式模拟injectEndpoints,尽管我不确定如何进行。如果有人遇到过类似的问题,或者在此设置中有模拟RTK查询的经验,您的建议将是非常宝贵的。

vc6uscn9

vc6uscn91#

所以答案很简单,我有一个循环依赖,为了解决这个问题,我使用了一个madge

npx madge --circular --extensions ts,tsx,jsx ./src

相关问题