How come the reducer is still updating the state with incorrect input in my test scenario?

I'm facing an issue with my reducer in Redux where it is supposed to only accept numerical values, but when I test it with non-numeric input, the state still gets updated. Why is my reducer not filtering out non-numerical inputs?

Here is how my action is defined:

  setCount: (count: number) => createAction(ActionTypes.SET_COUNT, {count})

This snippet shows the relevant code from my reducer:

case ActionTypes.SET_COUNT: {
  draft.count = action.payload.count;
  break;
}

And here is the unit test that I wrote:

 describe(`(Action) ${ActionTypes.SET_COUNT}`, () => {
    const unsuccessfulAction = Actions.setCount("bad input");

    it("Should not update the state for the count when input is not a number", () => {
      const state = myReducer(undefined, unsuccessfulAction);
      expect(state.count).toBe(null); 
    });
  });

Upon running the test case, I received "bad input" as the result while expecting null.

Answer №1

After analyzing your query, it is apparent that you have a reducer in place that assigns numerical values to the redux state.

The current code snippet displays how the 'count' property of the payload is being directly assigned to the 'count' property of the state:

case ActionTypes.SET_COUNT: {
  draft.count = action.payload.count;
  break;
}

However, the existing logic does not ensure that only numerical values are set in the state. To achieve this restriction, additional checks need to be added within the reducer function.

If you want to restrict the assignment to only numerical values, consider modifying the code as follows:

case ActionTypes.SET_COUNT: {
  if (isNumeric(action.payload.count)) {
    draft.count = action.payload.count;
  }
  break;
}

You will need to implement an appropriate version of the isNumeric function to facilitate this validation.

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

The use of PartialLinkText is ineffective when utilized in TypeScript

Below is a list of elements: <div class="container-menu" _ngcontent-c13=""> <nav _ngcontent-c13=""> <ul _ngcontent-c13=""> <li _ngcontent-c13=""> <a class="" _ngcontent-c13="" href="/32info" role="link" routerlinkactive="active" ...

Constructing an array in an asynchronous manner while simultaneously iterating through other arrays

In my attempt to create a comprehensive keyword list from the existing keywords, I successfully retrieved them all and displayed them in the debug console. However, I am facing confusion regarding the appropriate time and method to call resolve(taxonomyKe ...

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...

What is the best way to define a named, optional parameter in TypeScript-React that can accept an object with optional fields and default values?

Is there a way to achieve something similar to the style property found in default HTML components? For instance: <div ref={ref} style={{ overflow: 'visible', height: 600, width: '100%' }}> The style prop is optional, and the fie ...

Determine the category of a container based on the enclosed function

The goal is to determine the type of a wrapper based on the wrapped function, meaning to infer the return type from the parameter type. I encountered difficulties trying to achieve this using infer: function wrap<T extends ((...args: any[]) => any) ...

Angular Ionic calendar date selector

I'm encountering an issue while trying to implement a time picker with a minimum and maximum hour range from 10:00 am to 10:00 pm. Unfortunately, I have discovered that I cannot achieve this using the ion-datetime component. Are there any alternative ...

Tips for customizing components in React-Table by overriding default columns

In a nutshell, I was tasked with developing a table component using react-table. By default, the table uses an input component that allows instant typing when double-clicked. Additionally, I wanted one of the columns in editableCell to use a dropdown. I ...

In order for the argument to be valid, it is

Transitioning to Typescript has brought me immense joy for various reasons. While exploring its benefits, I encountered a challenge related to verifying if an argument passed to a function extends another class. Here is an example scenario: class Foo { ...

Steering clear of using relative paths in Angular CLI

I am currently using the most up-to-date Angular CLI and have set up a custom components folder to store all of my components. For instance, within the TextInputComponent, there is a TextInputConfiguration class located in src/components/configurations.ts ...

Error message: Uncaught ReferenceError: require is not defined in Typescript and KnockoutJs combination

Presently, I am exploring the ts-ko demo provided by TypeScript. When I directly reference Ko like this: /// <reference path="./node_modules/@types/knockout/index.d.ts" /> No errors occur. However, if I add a reference in this manner: import * as ...

What are the essential steps for effectively unit testing a React component?

When it comes to testing a react component, what are the recommended best practices and key elements to focus on? Typically in standard tests, I verify if the correct state and input produce the expected output. However, React components introduce a uniqu ...

Understanding how to infer type from the arguments of a class constructor in Typescript

Is there a way to reuse the argument type definition of a class constructor without refactoring or extracting it from the class itself? I have tried using GetProps<TBase>, but it doesn't work as expected. In the example below, the const bp defin ...

Ways to display only a specific color in an image

Looking to work with an image that contains predefined color blocks? Take this example picture as reference: https://i.sstatic.net/QlwvY.png Is there a method to display only certain colored areas while keeping the rest transparent? Note that no edge pat ...

Koffi organized a collection of structured arrays

I am currently using koffi 2.4.2 in a node.js application from koffi.dev and up until now, everything has been running smoothly. However, I have encountered an issue with integrating a native C++ library method that requires a parameter struct defined as f ...

How can one access a dynamically generated element in Angular without using querySelector?

Currently in the process of developing my custom toastr service, as shown in the GIF below https://i.sstatic.net/Zpbxs.gif My Objective: https://stackblitz.com/edit/angular-ivy-tgm4st?file=src/app/app.component.ts But without using queryselector. It&apos ...

Is there a way to initiate a mouse click and drag action in amCharts v5?

I am currently utilizing the capabilities of amCharts v5 to create a similar functionality to this particular example from amCharts v3. In the sample scenario, an event is triggered by the property "chart.isMouseDown" and alters the position of bullets ba ...

Exploring the Power of Angular's Redux Implementation with Lazy Loading Strategy

Implementing Redux with Angular has been incredibly beneficial for me, but I am curious about how lazy loading can be incorporated alongside it. Can these two techniques work well together? ...

Functional programming: Retrieve the initial truthy output from executing an array of diverse functions using a particular parameter

As I delve into the world of functional programming in TypeScript, I find myself contemplating the most idiomatic way to achieve a specific task using libraries like ramda, remeda, or lodash-fp. My goal is to apply a series of functions to a particular dat ...

Is there a way to dynamically update the Material UI theme through the Redux store?

Here is a React component using a custom Material UI theme We have the following code snippet: const getTheme = name => themes.filter(theme => theme.name === name)[0] || themes[0]; const Root = props => ( <MuiThemeProvider muiTheme={getM ...

Using asynchronous data in Angular 2 animations

Currently, I have developed a component that fetches a dataset of skills from my database. Each skill in the dataset contains a title and a percentage value. My objective is to set the initial width value of each div to 0% and then dynamically adjust it t ...