Configuring Redux Provider for Jest Testing

I'm currently working on setting up a redux provider for Jest testing in my react app. To achieve this, I believe I need to implement the following code snippet:

import {ReactNode} from 'react'
import {Provider} from 'react-redux'
import {store} from "../redux/reducer/store";

type PropsWithOptionalChildren<P = unknown> = P & { children?: ReactNode };
type RootState = ReturnType<typeof store>    
interface ReduxProviderProps extends PropsWithChildren {
    store: RootState,
}

const ReduxProvider = ({children, store}: ReduxProviderProps) => <Provider store={store}>{children}</Provider>

export default ReduxProvider

This setup can then be used as shown below:

test("...", () => {
  const store = configureStore();
  const wrapper = ({ children }) => (
    <ReduxProvider reduxStore={store}>{children}</ReduxProvider>
  );
  ...
});

However, I am encountering an issue with the following line of code:

type RootState = ReturnType<typeof store>

The type [...] does not meet the constraint (...args: any) => any The type [...] does not match the signature (...args: any): any

This error seems to be related to the store variable

export const store = configureStore({
    reducer: persistedReducer,
    devTools: process.env.NODE_ENV !== 'production',
    middleware: getDefaultMiddleware =>
        getDefaultMiddleware({
            serializableCheck: false
        }).concat(apiSlice.middleware),
});

In addition, here is some more context:

export const rootReducer = combineReducers({
    a: aReducer,
    b: bReducer,
    [apiSlice.reducerPath]: apiSlice.reducer,
})

const config = getPersistConfig({
    key: 'root',
    storage,
    blacklist: ['a'],
    rootReducer
})

const persistedReducer = persistReducer(config, rootReducer)

What would be the best approach to solve this compiler error?

Answer №1

Give this a shot:

const RootState = ReturnType<typeof store.getState>;

Answer №2

To potentially resolve the issue, consider modifying the RootState type as shown below:

type RootState = ReturnType<typeof store.getState>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the power of image uploads with reactive forms in Angular 7 integrated with Firebase

At the moment, I am developing a basic CRUD Angular application with Firebase as the backend. The app consists of a simple table displaying a list of students. When it comes to adding a new student, a popup appears with fields for name, group, mark, and ...

Adding video files and subtitle files to our MongoDB database

// backend/server.ts import express, { Application, Request, Response } from 'express'; import mongoose from 'mongoose'; import cors from 'cors'; import dotenv from 'dotenv'; const multer = require('multer&apos ...

Bring in all Functions and Interfaces from the Types Definition

How can I call the function below in TypeScript: nlp.text("Hi Dr. Miller the price is 4.59 for the U.C.L.A. Ph.Ds.").sentences.length // 1 To make this function call work, what would be the correct import statement needed from this types definition? It& ...

What is the correct method for importing React in TypeScript (.tsx) to ensure optimal integration?

Within our TSX/React web application, we employ two distinct import styles for the react module: import * as React from "react"; as well as import React from "react" As far as I know, both methods function without any noticeable differences. Is there a ...

Tips for stopping webpack from creating compiled files in the source directory

I'm in the process of transitioning my AngularJs project from ES6 to TypeScript and I've integrated webpack with ts-loader. However, I've encountered an issue where the compiled files and source maps are saved in my directory instead of bei ...

An internal issue has occurred: RangeError: The call stack limit has been exceeded in Next.js React

Recently, I've encountered the error message "⨯ Internal error: RangeError: Maximum call stack size exceeded" and I'm struggling to pinpoint the root cause of this issue. My goal is to have the functionality where clicking the "Add to Cart" but ...

Whenever I try to utilize async with React.FC in my React component, a TypeScript error is thrown

I am currently working on a React functional component called DashboardPage that utilizes async/await for fetching data, but I am running into a TypeScript error. The specific error message reads: 'Type '({ params }: DashboardPageProps) => Pro ...

Instance property value driven class property type guard

Is it possible to create a class example that can determine the config type based on the value of animalType instance: enum Animal { BIRD = 'bird', DOG = 'dog', } type Base = { id: number } // Object example type Smth = Base & ...

Redux application is not functioning properly

I followed the official documentation to create a Redux app at http://redux.js.org/docs/basics/ but it's not working as expected. I have organized my code into four files: store, reducers, actions, and build. actions.js: export const ADD_TODO = &apo ...

What is the best way to identify if a variable in typescript is null?

Initially, I will perform an HTTP request to a URL in order to retrieve some data. { "data": { "user": { "name": "john", "other": [{ "a": 1, "b": 3 }] } } } My go ...

Reduce the use of if statements

Is there a way to optimize this function by reducing the number of if statements? The currentFeatures are determined by a slider in another file. The cost is updated if the currentFeatures do not match the previousFeatures, and if the user changes it back ...

The comparison between serialization at the PostgreSQL layer and the application layer

I have come across limited information and opinions on this topic. When it comes to serialization, is it better to perform it directly on the SQL layer (specific column selection) or is it acceptable for performance reasons to retrieve the entire record ( ...

Validate object containing both static and dynamic keys

I'm attempting to create a Yup validation schema for an object with the following structure: interface myObject { prop0: Date prop1: { nestedProp1: string nestedProp2: number [key: string]: string | number } } This is what I have tr ...

[Nuxt.js/Typescript] Accessing Vuex data in Nuxt.js using Typescript

Hello, I am new to Typescript and I have encountered an issue with setting Objective Data to Vuex store. Here is the Objective data of Users (also known as account). # models/User.ts export interface IUser { email: string | null name: string | null ...

The relationship between Vue TypeScript props is influenced by the presence of another prop

Is there a way to define a property in <script setup lang="ts"> that depends on another property? For instance, how can I require a variable only if another variable is present? I attempted using defineProps<Props | PropsA>(), but e ...

Clicking on the Angular custom accordion component does not trigger the expansion feature

I have developed a customized accordion component using Angular 9, but I am encountering an issue. Whenever I click on the accordion, only the first button's window expands while the others remain unaffected. To demonstrate the problem more effective ...

My component is displaying a warning message that advises to provide a unique "key" prop for each child in a list during rendering

I need help resolving a warning in my react app: Warning: Each child in a list should have a unique "key" prop. Check the render method of `SettingRadioButtonGroup`. See https://reactjs.org/link/warning-keys for more information. at div ...

initiating nest start removes the json files in the dist directory

As I work on my nestjs application, I find myself needing to ensure that specific json files are copied to the dist directory. This is especially important for the "engines" folder, where the json files in src/engines must be replicated in dist/and prod. ...

Preventing Event Propagation in Angular HTML

I am encountering an issue with stopPropagation, and I need assistance with implementing it in HTML and TypeScript for Angular. The problem is that the dialog opens but also triggers a propagation. Below is my code snippet in HTML: <label for="tab-two ...

Retrieving All Relationship Information in AdonisJS

Is there a way to fetch all the data, including related data in AdonisJS? I am looking to retrieve user data from the User Model along with its relationships in the Post Model. Get All Users public async getUsers({ response }: HttpContextContract) { ...