RTK Query+Firebase点餐应用集成测试求助:Store使用与类型错误
基于RTK Query与Firebase的点餐应用购物车组件测试问题
我开发了一款基于RTK Query与Firebase的点餐应用,目前要对购物车组件做集成测试,遇到两个问题:
- 不确定测试渲染购物车组件时,能否直接包裹带有RTK Query reducer的实际Redux Store
- 自行编写的测试辅助文件
helpers.tsx出现TypeScript类型错误,想确认这套测试方案是否可行
以下是相关代码片段:
RTK Query API定义
export const api = createApi({ baseQuery: fakeBaseQuery(), reducerPath: 'api', tagTypes: ['GetCartItems'], endpoints: (build) => ({ getCartItems: build.query<"notExists" | GetCartItemsReturn, string>({ async queryFn(user) { try { const cartDocRef = doc(db, `cart/${user}`) // 其他Firebase操作逻辑 } } }) }) }) export const { useUpdateCartMutation, useGetCartItemsQuery, useDeleteCartItemMutation } = api
Redux Store配置
import { configureStore } from "@reduxjs/toolkit"; import { api } from "../RTKQuery/cartQuery"; export const appStore = configureStore({ reducer: { [api.reducerPath]: api.reducer }, middleware: (getDefaultMiddleware) => { return getDefaultMiddleware({ serializableCheck: false, }).concat(api.middleware) }, })
购物车组件片段
const Cart = () => { const { user } = useContext(userContext) const [updateCart] = useUpdateCartMutation() const [deleteCart] = useDeleteCartItemMutation() const { data: cartItem } = useGetCartItemsQuery(user?.uid!) // 组件逻辑与Firebase交互逻辑 }
测试辅助文件helpers.tsx
import React, { PropsWithChildren } from "react"; import { render as rtlRender } from "@testing-library/react"; import { configureStore } from "@reduxjs/toolkit"; import { api } from "../../RTKQuery/cartQuery"; import { Provider } from "react-redux"; import type { PreloadedState } from '@reduxjs/toolkit' import { RootState } from "../../store/appStore"; type preloadState = PreloadedState<RootState>; const initalState = { api: { restaurantId: '737440', itemWithQuantity: { 127533210: 1 }, queries: {}, mutations: {}, provided: {}, subscriptions: {}, config: {} } }; function render( ui: React.ReactElement, { preloadedState = {} as preloadState, store = configureStore({ reducer: { [api.reducerPath]: api.reducer, }, preloadedState, middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware), }), ...renderOptions } = {} ) { // 渲染包裹逻辑 } export * from "@testing-library/react"; export { render };
错误信息
'preloadedState' 隐式拥有 'any' 类型,因为它没有类型注解,且在自身初始化器中直接或间接被引用。ts(7022) (parameter) preloadedState: any
内容的提问来源于stack exchange,提问作者Ranjana Singanoodi
相关产品推荐
相关产品推荐

