Cypress with Typescript: Best ways to retrieve specific values from a dataTable

I am facing an issue with a data table that contains a list of states and messages which I need to validate in a particular scenario.

Given user inputs "<state>" and sees "<message>" message
        | state       | message      |
        | Deactivated | error        |
        | Taken       | error        |
        | Unused      | confirmation |

Despite my efforts, the script provided below only executes actions based on the 'state' values without considering the corresponding 'message' actions.

Given(‘user inputs {string} and sees {string} message’, (dataTable: DataTable) => {

dataTable.hashes().forEach(elem =>{
        if(elem.state == 'Deactivated') {
            <DeactivatedAction>
        } else if(elem.state == 'Taken') {
            <TakenAction>
        } else if(elem.state == 'Unused') {
            <UnusedAction>
        } else {
            throw new Error("No state defined")
        } 
    })

dataTable.hashes().forEach(elem =>{
        if(elem.message == 'error') {
            <errorAction>
        } else if(elem.message == 'confirmation') {
            <confirmationAction>
        } else {
            throw new Error("No state defined")
        } 
    })
}

Even when attempting to change from .forEach() to .map(), the issue persists. :/

Answer №1

If my understanding is correct, you are looking to have the 2nd loop access "message", but it seems like there may be a typo - you are referencing elem.state instead of elem.message.

dataTable.hashes().forEach(elem => {
  if (elem.message === 'error') {
    <errorAction>
  } else if (elem.message === 'confirmation') {
    <confirmationAction>
  } else {
    throw new Error("No state defined")
  } 
})

Answer №2

Combining the loops technically should ensure that both sections function correctly

dataTable.hashes().forEach(elem => {
  if (elem.state == 'Deactivated') {
    <DeactivatedAction>
  } else if (elem.state == 'Taken') {
    <TakenAction>
  } else if (elem.state == 'Unused') {
    <UnusedAction>
  } else {
    throw new Error("No state defined")
  } 

  if(elem.message == 'error') {
    <errorAction>
  } else if(elem.message == 'confirmation') {
    <confirmationAction>
  } else {
    throw new Error("No state defined")
  } 
})

However, it seems there may be a potential link between the state and message within the row,

function doMessage(message) {
  if(message == 'error') {
    <errorAction>
  } else if(message == 'confirmation') {
    <confirmationAction>
  } else {
    throw new Error("No state defined")
  } 
}

dataTable.hashes().forEach(elem => {
  if (elem.state == 'Deactivated') {
    <DeactivatedAction>
    cy.then(() => doMessage(elem.message))

  } else if (elem.state == 'Taken') {
    <TakenAction>
    cy.then(() => doMessage(elem.message))

  } else if (elem.state == 'Unused') {
    <UnusedAction>
    cy.then(() => doMessage(elem.message))

  } else {
    throw new Error("No state defined")
  } 
})

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

Error encountered while building with Next.js using TypeScript: SyntaxError - Unexpected token 'export' in data export

For access to the code, click here => https://codesandbox.io/s/sweet-mcclintock-dhczx?file=/pages/index.js The initial issue arises when attempting to use @iconify-icons/cryptocurrency with next.js and typescript (specifically in typescript). SyntaxErr ...

Dealing with errors when implementing an Angular 2 route guard that returns an Observable of type boolean can be a

My route guard is implemented as follows: @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router, private authenticationSvc: AuthenticationService) { } canActivate(): Observable<boolean> { return this. ...

Deactivate the button until the input meets validation criteria using Angular

What I'm trying to achieve is to restrict certain input fields to only accept integer or decimal values. Here's the code snippet that I currently have: <input type="text" pattern="[0-9]*" [(ngModel)]="myValue" pInputText class="medium-field" ...

Unable to simulate a static method in Vitest - encountering an error stating "is not a function"

I am currently writing unit tests using the Vitest framework for my TypeScript and React application, but I have encountered an issue with mocking static methods. Below is a snippet of my code: export class Person { private age: number; constructor(p ...

JavaScript - Employing the .every function with an array containing objects

Is it possible to use the array.every method on multidimensional arrays? The structure of my array is as follows: tabs=[ {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: ...

The reason for the Jest failure is that it was unable to locate the text of the button

As someone who is new to writing tests, I am attempting to verify that the menu opens up when clicked. The options within the menu consist of buttons labeled "Edit" and "Delete". However, the test fails with the message: "Unable to find an element with te ...

Angular HighCharts - Retrieving chart data via API

My goal is to populate the data property of my chart with values obtained from an external API: . I've defined an Interface that matches the structure of the data: export interface ChartData{ item1: number; item2: number; ...

Can we define the input and return types for functions using httpsCallables?

I have implemented a callable function in my app to update user claims. The functions are written in Typescript and I have used an interface to define the required data shape for the function. My objective is to make it easier for any developer on the tea ...

Unable to clear all checkboxes after deleting

In my application, there are 3 checkboxes along with a master checkbox that allows users to select or deselect all of them at once. Everything works fine with the master checkbox until I delete some rows from the table. After deleting data, I can check th ...

TypeScript's standard React.Children interface for compound components

One of my components is a Table, which can have children that are Column components: <Table data={data}> <Column cell={(c) => c.date} header="Date" /> <Column cell={(c) => c.count} header="Count" /> & ...

Protected asynchronous request

I am working with a dataTable that has server-side processing, but I am uncertain about how to secure the ajax call, as accessing the ajax php file directly could potentially expose all the content. Below is the jQuery code I am using: $(document).ready( ...

Using string interpolation within the onclick event (Ionic 2 + Angular 2)

One question that's troubling me - I'm attempting to pass a string within an "onclick" event in my Ionic 2 app, but it keeps throwing an error. <button onclick="window.plugins.socialsharing.shareViaWhatsApp(null, null, '{{sound.file}}&a ...

Error TS2339: The 'selectpicker' property is not found on the 'JQuery<HTMLElement>' type

Recently, I integrated the amazing bootstrap-select Successfully imported bootstrap-select into my project with the following: <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstra ...

Sharing information between different pages in NEXT.js version 14

After performing a fetch and receiving a successful response containing data as an object, I use router.push to redirect the page to another one where I want to display the fetched data. const handleSubmit = async (event: any) => { event.preventDefa ...

Issue with toggling in react js on mobile devices

Currently, I am working on making my design responsive. My approach involves displaying a basket when the div style is set to "block", and hiding it when the user browses on a mobile device by setting the display to "none". The user can then click on a but ...

There is no module.hot in Webpack for TypeScript

I am trying to implement Webpack HMR in a NodeJS project that is built using TypeScript. However, I am encountering an issue where module.hot is not available: @types/webpack-env defines: declare var module: __WebpackModuleApi.Module This conflict ...

Tips for adjusting card content to fit its size in material ui?

I'm looking to implement Material UI cards in a grid layout, each containing a Highcharts chart as shown in this demo. However, I'm facing an issue where the content does not adjust properly when the card size is fixed. How can I resolve this? A ...

What is the process for implementing custom color props with Material-UI v5 in a React TypeScript project?

Looking to enhance the MUI Button component by adding custom color props values? I tried following a guide at , but encountered errors when trying to implement it in a custom component. The custom properties created in createPalette.d.ts did not work as ex ...

Svelte warns of potential undefined Variable when using "bind:this={}"

Whenever I attempt to utilize the bind:this attribute in Svelte, I encounter this message in vscode: 'cardGroup' is possibly 'undefined'.js(18048) Upon execution, the following error arises: TypeError: Cannot read properties of undefin ...

Combining multiple data types in an AJV array

Imagine you have the following defined type: type MixedArray = Array<number | string>; Now, let's say you have some sample data that needs to be validated: [ 'dfdf', 9, 0, 'sdfdsf' ] How can you create an Ajv JSONSchemeType ...