The absence of a type in AnyAction is causing a TypeScript error in react testing

I ran into an issue and received the following error message:

TS2345: Argument of type '(dispatch: Dispatch) => Promise<void>' is not assignable to parameter of
type 'AnyAction'.   Property 'type' is missing in type '(dispatch: Dispatch) => Promise<void>' but
required in type 'AnyAction'. type' is declared here* :

* The declaration code is as follows:

export interface Action<T = any> {
  type: T
}

The AnyAction extends the Action interface.

This snippet shows my test code:

import configureStore from 'redux-mock-store';
import reduxThunk from 'redux-thunk';
// some code, then in the test I have:

const mockStore = configureStore([reduxThunk]);
const store = mockStore({});

store.dispatch(signIn()); //this line triggers the error

The definition of the signIn function is as follows:

export const signIn = () =>
  async (dispatch: Dispatch): Promise<void> => {
    dispatch({
      type: SIGN_IN_REQUEST
    });
  };

Does anyone have a suggestion or idea on how to resolve this issue?

Answer №1

When using configureStore, we can provide arguments to express dispatch extensions. To ensure compatibility with redux-thunk, we need to include ThunkDispatch as an argument, like this:

import { ThunkDispatch } from 'redux-thunk';

// defining the app state
interface AppState {}

// you can also add more parameters for `ThunkDispatch`
const exampleStore = configureMockStore<AppState, ThunkDispatch<AppState, any, any>>([])

Answer №2

After reviewing tmho2005's response and consulting a similar thread, I was able to come up with the following code snippet for anyone in need:

// Relevant code specific to the query
import { AnyAction } from 'redux';
import configureStore from 'redux-mock-store';
import reduxThunk, { ThunkDispatch } from 'redux-thunk';

import { AuthState } from '../../../types'; // Defines the application state

type DispatchExts = ThunkDispatch<AuthState, void, AnyAction>;

// Code for running tests:

const mockStore = configureStore<AuthState, DispatchExts>([reduxThunk]);
const store = mockStore(defaultState);

await store.dispatch(signIn({
  username: 'foo',
  password: 'bar'
}));

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

JavaScript has a feature called "functions" which allow the declaration of named blocks of

Currently, I am developing an Electron app in typescript. In my main.ts file, I have instantiated a custom CommunicationProvider class object. What I want is for this class to declare multiple methods (specified in an interface that it implements) but have ...

const error = new TypeError(`${calculateRelativePath(cwd, fileName)}: Skipping emission of file`);

Hey there! I have a typescript code snippet that looks like this: import { getConnection } from "typeorm"; import { GraphQLClient } from "graphql-request"; import got from "got"; import database from "./utils/database&quo ...

Issue: The Auth Interceptor is expecting a stream but received 'undefined'. Please provide an Observable, Promise, Array, or Iterable instead

I am facing an issue where I need to intercept every request to api, check the status code, and display a message or redirect to a specific component. However, I keep encountering the following error: main.js:1580 TypeError: You provided 'undefined ...

What is the best way to incorporate a background image using ngStyle?

I need help populating multiple cards in the following way: <mdl-card *ngFor="let product of templates" class="demo-card-event" mdl-shadow="2" [ngStyle]="{ 'background-color': 'lightgray' }"> <mdl-card-title mdl-card-expan ...

Error message thrown when attempting to access Navigator InjectionToken in tests: ReferenceError - Navigator is not defined

I have created an abstraction for the Navigator object: export const NAVIGATOR: InjectionToken<Navigator> = new InjectionToken<Navigator>( 'An abstraction over window.navigator object', { factory: () => inject(WINDOW).navig ...

What is the method for expanding an object type using a string literal type?

I am encountering an issue with the code snippet below. In this code, type B is meant to extend type A by expanding the acceptable values for the property type. However, despite this intention, the assignment is resulting in a type error. type A = { ...

The entire space should be filled with the background

My goal is to achieve the following while addressing some current issues: The background is currently limited to affecting only the container. I want it to span the entire area. There needs to be space between the cards and padding inside them. https://i ...

An issue has been detected by Zone.js where the ZoneAwarePromise `(window|global).Promise` has been unexpectedly replaced

I have recently integrated the Angular2 quickstart code into my existing webpack setup, but I seem to be facing an issue where something is interfering with the promise from zone.js, resulting in an error. Based on my research on Stack Overflow, it appears ...

What is the best way to access the second item using getByRole in React Testing Library when there is no specific name?

I am familiar with using the name option to select the first item here, but how can I go about selecting the second item if it does not have a name identified? -------------------------------------------------- button: Enter "Go": ...

Incorporate matter-js into your TypeScript project

Upon discovering this file: https://www.npmjs.com/package/@types/matter-js I ran the following line of code: npm install --save @types/matter-js When I tried to use it in the main ts file, an error message appeared: 'Matter' refers to a U ...

Tips for utilizing a ternary operator to set a className in an element

I'm in the process of developing a website using React and Next.js. One of the components on my site is section.tsx, which displays a subsection of an article based on the provided props. I'm looking to add an 'align' property to this c ...

What is the term for specifying a variable's data type using a set of values instead of a traditional type?

Recently, I stumbled upon some code that introduces a class with specific variables defined in an unconventional manner. export class Foo { id: string = "A regular string" bar: '>' | '<' | '=' | '<=' | ...

Transmit data via XMLHttpRequest in smaller portions or through a ReadableStream to minimize memory consumption when handling large datasets

Recently, I've been experimenting with JS's XMLHttpRequest Class for handling file uploads. Initially, I attempted to upload files using the following code: const file = thisFunctionReturnsAFileObject(); const request = new XMLHttpRequest(); req ...

Unable to append element to array in TypeScript/Angular

Programming Environment: Angular 6 export class Student { fullName: string; age: number; classType: string; } export class MyClass { public resultData: Array<Student> = []; processedData = { studentData: [ { ...

Compilation error in VueJS: missing dependency detected

I am facing an issue in my VueJS project where a file I am referencing seems to be causing a compilation error. Despite being present in the node_modules directory, the dependency is declared as not found. In the image on the left, you can see the directo ...

What are some ways to control providers in targeted tests using ng-mocks?

I recently started utilizing ng-mocks to streamline my testing process. However, I am struggling to figure out how to modify the value of mock providers in nested describes/tests after MockBuilder/MockRender have already been defined. Specifically, my que ...

An item whose value is determined by the specific type of key it possesses

Consider the following scenario: enum MouseType { GENERAL_USE = 1, SPECIALIZED_USE = 2, } enum KeyboardType { GENERAL_USE = 3, SPECIALIZED_USE = 4, } interface MouseSpecifications { buttons: number; dpi: number; } interface KeyboardSpecifica ...

Guide for setting up filtering and sorting on a multi-value array column with MUI's data grid

I've encountered an issue with the MUI Data Grid component's free version, specifically regarding filtering and sorting on a column that displays multiple values in an array. The problematic column in this case is 'tags', which showcase ...

Show the interface value for an array type

I have created a component to display API data. The structure of the component is as follows: HTML: <div *ngFor="let customer of customers"> <p>Name: {{customer?.name}}</p <p>Phone: {{customer?.phoneNumbers}}</p </div&g ...

Class field type based on generics

Consider the code snippet below in the playground: type AvailableTypes = { 'array': Array<any>; 'string': string; 'object': object; } class Wrapper<T extends keyof AvailableTypes> { // Can be of ...