Why isn't the unit test passing when it clearly should be?

I am encountering an issue with testing a simple function that I have created. Despite the fact that the function works correctly in practice, it is not being tested properly...

Explanation of how my function operates (While it functions as intended, the test outcome is incorrect)

  1. I input a string into the function
  2. If the input matches an element in my array,
    1. The function returns the string
  3. If there is no match with any array element
    1. The function returns the string 'default'

However, upon running the test provided, I encounter the following error:

Expected 'default' to equal 'hare-failure

Function Code

const state = [
   {name: 'failure'}
];

isStatus(current): string {
    for (const status of this.state) {
      if (status.name === current) {
        return current;
      }
    }
    return 'default';
  }

Test Case

beforeEach(async(() => {

    TestBed.configureTestingModule({
      declarations: [EventComponent, ConfirmationComponent],
      imports: [ReactiveFormsModule, FormsModule],
      providers: []
    });

    fixture = TestBed.createComponent(EventComponent);
    component = fixture.componentInstance;
    component.ngOnInit();
  }));

it('should return current status if it is part of exceptional statuses', () => {
    const returned = component.isState('failure');
    expect(returned).toEqual('failure');
  });

Answer №1

Avoid using the for-of loop in this instance. Consider refactoring the component to utilize the some() method for Arrays and implement a pure function.

Instead of:

isStatusExceptional(currentStatus): string {
for (const status of this.exceptionalRaceStatuses) {
  if (status.name === currentStatus) {
    return currentStatus;
  }
}
return 'default';

}

you can write:

isStatusExceptional(current, erc = this.exceptionalRaceStatuses): string {
  return erc.some(item => item.name === current) ? current : 'default';
}

Answer №2

It seems like the issue might be with using const instead of let in your loop. When you use const, it prevents reassignment of the value as the loop progresses, so switching to let could solve the problem.

isStatusExceptional(currentStatus): string {
    for (let status of this.exceptionalRaceStatuses) {
      if (status.name === currentStatus) {
        return currentStatus;
      }
    }
    return 'default';
  }

According to the Typescript docs, it looks like they support this reasoning as well.

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

What is the best way to create individual Menu items in a React/MUI navigation bar?

I am currently developing a navigation bar for an application, and I seem to be facing an issue with differentiating between multiple Menu/MenuItem elements. No matter what approach I take, both Menus and their respective MenuItems end up directing to the ...

How can I resolve the issue of a lengthy link spanning two lines in Internet Explorer, while displaying correctly in other browsers on a Bootstrap navigation

Currently in the process of developing a responsive website with Bootstrap. The navigation buttons at the top are displaying correctly in Chrome, Safari, and Firefox, but in IE, the button labeled "Public Consultation" is wrapping onto two lines. I suspec ...

An error of type TypeError occurred while attempting to browserify a module in a Node.js environment

Is there a way to integrate this algorithm into a client-side function? I'm looking to use the RAKE Module within a browserified function on the client side. You can find the RAKE Module on GitHub here: https://github.com/waseem18/node-rake To compi ...

What causes a Typescript error when attempting to escape a newline character?

My approach is quite simple: I concatenate multiple strings and format them to make them more readable. info() { return "x: " + this.xpos.toString() + "\n" \ + "y: " + this.ypos.t ...

I am converting a class component to a functional component within a React-Redux-Firebase project

I am currently in the process of rebuilding this component. Check out the updated code here Also, take a look at the project actions script here However, I'm facing an issue with rewriting mapStateToProps and mapDispatchToProps functions. The error ...

Issues related to the performance of React, Redux, and three.js

UPDATE: After identifying the issue, I have narrowed it down to this small gist and this jsfiddle. In my real-time 3D game based on three.js, I intended to utilize Redux for state management. Despite creating a simple prototype for testing purposes, even ...

Rendering React components in a predetermined sequence for an interactive user experience

I am working with a component that includes multiple images and I need to render them dynamically based on predetermined data. <ImageComponent image={this.props.data.image1} /> <ImageComponent image={this.props.data.image2} /> <Imag ...

How to implement a delay for submenu dropdown in Bootstrap 3

I am trying to implement a delay on a submenu that I have created, rather than the entire bootstrap3 dropdown menu. The goal is to allow users to easily move their cursor to the submenu without it closing unexpectedly. Although the jquery code should still ...

Child components are not able to access properties from the root component in VUE3

Hi there! I'm currently learning VUE3 and had a question about defining global properties in the Root Component. I did some research on Google before posting this question, but couldn't find any relevant results. I would like to set a global pro ...

Is there a way to extract information from an external XML document and incorporate it into an HTML file?

I am attempting to extract information from an XML file that is not stored on my website's server. My goal is to utilize this data for various purposes, such as generating charts. One specific example involves using weather data from an XML file locat ...

Utilizing the Global Module in NestJs: A Step-by-Step Guide

My current project is built using NestJS for the back-end. I recently discovered that in NestJS, we have the ability to create Global Modules. Here is an example of how my global module is structured: //Module import {Global, Module} from "@nestjs/commo ...

Every time I attempt to use interpolation in Angular 11, the result ends up being displayed as plain text on

I'm a beginner in Angular and I recently attempted my first code following a tutorial. When running this code on a live server using port 5500, I encountered an issue with interpolation. <h1>{{title}}</h1> The result on the webpage displa ...

issue with lazy loading Angular module containing a preview component

Greetings everyone! I successfully created an Angular app with lazy loading, but I encountered an issue when trying to open child pages inside modules. Instead of opening within the main page, it redirects me to a new page. Here is my module structure: co ...

Troubleshooting Images in a React Application Integrated with WordPress API

I am struggling to understand why this GET request is consistently returning a 404 error. I have thoroughly tested the URL using Postman and everything seems to be in working order for the title and excerpt, but the images are causing some issues. Does a ...

The Discord.js .cleanContent attribute does not show up when using Object.keys() and cannot be logged

My Discord.js Message object should contain a property called .cleanContent, according to the documentation, and it should be a string. console.log(message.cleanContent) works correctly, but console.log(message) does not display the cleanContent propert ...

Selecting items from a list at random using the power of math.random() and math.floor()

When attempting to randomize the popping of elements in a list stored in the baby variable, only baby[1] is being popped. How can I make it pop random elements? <body> <h1 id="1">bebe</h1> <h1 id="2">t ...

Preserve the wpColorPicker selection using personalized knockout bindings

Utilizing wpColorPicker and knockout, my goal is to update the color picker value in my observable and then store it in the database as JSON. While other elements successfully update and save, there seems to be an issue with my custom binding for the data ...

What are the steps to store and access state variables using session storage in a React application?

I am currently utilizing React version 18.2.0. In my application, I have a component called BodyComponent that stores the data retrieved from an API call in its state as results, along with some filter information in filters. The BodyComponent fetches the ...

What are some strategies for increasing efficiency in my drag and drop process?

Update #2 Wow, transition was stuck at .35s. My CSS just wasn't updating properly :( UPDATE: Anyone know if requestAnimationFrame could help with this? I've got a rotating image reel and I want users to be able to swipe left or right to switch ...

Passing backend variables/data to AngularJS in Express JS

As a newcomer to express js, I appreciate your patience with me. I've been diving into "MEAN Web Development" by Amos Q. Haviv and finding it to be an excellent read. However, there's one part that's leaving me puzzled. It seems that in or ...