The parameter cannot be assigned because it is of type 'string | Date', not of type 'Date'

As I attempt to create a test suite with date mocking, I encounter an error stating 'Argument of type 'string | Date' is not assignable to parameter of type 'Date''. Below is the function:

const getDay = (inputDate: any, today = new Date()) => {
  const reportDate = new Date(inputDate)
  if (today >= reportDate) {
    const differenceInTime = today.getTime() - reportDate.getTime()
    const differenceInDays = differenceInTime / (1000 * 3600 * 24)
    const finalDayDiff = Math.floor(differenceInDays)
    if (finalDayDiff === 0) {
      return translate("common.today")
    } else if (finalDayDiff === 1) {
      return finalDayDiff + translate("common.dayAgo")
    } else {
      return finalDayDiff + translate("common.daysAgo")
    }
  } else {
    return ""
  }
}

The failing test suite highlights the testName and todayDate in red.

import { getDay } from "../common-functions"
import { translate } from "../../i18n/translate"

describe("checkForDifferenceInDays", () => {
  Array.of(
    [
      "1. difference in days - 1 day ago",
      new Date("2021-03-18T00:00:00.000Z"),
      1 + translate("common.dayAgo"),
    ],
    [
      "2. difference in days - 5 day ago",
      new Date("2021-03-22T00:00:00.000Z"),
      5 + translate("common.daysAgo"),
    ],
    [
      "3. difference in days - today",
      new Date("2021-03-17T00:00:00.000Z"),
      translate("common.today"),
    ],
    ["4. empty string", new Date("2021-03-15T00:00:00.000Z"), ""],
  ).forEach((testCase) => {
    const [testName, todayDate, expectedResult] = testCase
    const reportDate = "2021-03-17T00:00:00.000Z"
    test(**testName**, () => {
      //Act
      const actualResult = getDay(reportDate, **todayDate**)
      //Assert
      expect(actualResult).toEqual(expectedResult)
    })
  })
})
Highlighted in bold indicates an error. Can someone provide guidance on what I may be missing?

Answer №1

This array contains a mix of strings and dates:

[
  "1. difference in days - 1 day ago",
  new Date("2021-03-18T00:00:00.000Z"),
  1 + translate("common.dayAgo"),
],

Using `Array.of` is unnecessary in this scenario. For precise typing of the array elements, it should be declared as a constant array:

([
    [
      "1. difference in days - 1 day ago",
      new Date("2021-03-18T00:00:00.000Z"),
      1 + translate("common.dayAgo"),
    ],
    ...
  ] as const).forEach(...)

Answer №2

Your current test case functions on an array structure where each inner array contains elements of either type string or Date. In TypeScript, this can be explicitly defined as type (string | Date)[][] or

Array<Array<string | Date>>
.

An alternative approach could be using an array of tuples instead of arrays in this scenario. This can be explicitly expressed in TypeScript as type [string, Date, string][] or

Array<[string, Date, string]>
. Tuple elements provide a more specific typing and might work better when handling the elements within your forEach callback function.

To enhance clarity, I have made some slight modifications to your code. I hope you find them helpful.

import { getDay } from "../common-functions"
import { translate } from "../../i18n/translate"

describe("checkForDifferenceInDays", () => {
  const arr: [string, Date, string][] =
    [
      [
        "1. difference in days - 1 day ago",
        new Date("2021-03-18T00:00:00.000Z"),
        1 + translate("common.dayAgo")
      ],
      [
        "2. difference in days - 5 day ago",
        new Date("2021-03-22T00:00:00.000Z"),
        5 + translate("common.daysAgo"),
      ],
      [
        "3. difference in days - today",
        new Date("2021-03-17T00:00:00.000Z"),
        translate("common.today"),
      ],
      [
        "4. empty string",
        new Date("2021-03-15T00:00:00.000Z"),
        ""
      ]
    ]

  arr.forEach((testCase) => {
    const [testName, todayDate, expectedResult] = testCase
    const reportDate = "2021-03-17T00:00:00.000Z";
    test(testName, () => {
      //Act
      const actualResult = getDay(reportDate, todayDate);
      //Assert
      expect(actualResult).toEqual(expectedResult);
    })
  })
})

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

Creating a paragraph from text inputs using React

I'm currently working on code that retrieves input from two textboxes - one for a string value and one for a number value. I want this data to be displayed in real-time within a paragraph without the need for a submit button. I've been struggling ...

"Exploring the process of transferring an ID from one service to another using the select feature in Angular

I need to store the ID I receive from one service into another using the select element. Here is my approach: <select class="form-control" id="select_fac" [(ngModel)]="rep.idfac"> <option selected disa ...

Converting Typescript Object Types to Array Types with Tuple Structures

Presently, I have the following: interface Obj { foo: string, bar: number, baz: boolean } The desired outcome is to convert this interface into the tuple format below: [string, number, boolean] Is there a way to achieve this conversion? Up ...

Updating class with jQuery based on dynamically changing content

I am using countdown.js to create a custom countdown timer. My goal is to replicate the countdown timer seen on the homepage, but with the ability to change the target date (which I have already accomplished). Here is an example of what I currently have f ...

React URL displaying query

I am currently developing a React app using HashRouter. Within the app, there is a form with inputs where, after the user submits data, some of the information ends up in the URL like this: http://localhost:3000/?State=Alabama#/profile However, it should ...

Troubleshooting React-Redux: Button click not triggering action dispatch

I am facing an issue where my action is not being dispatched on button click. I have checked all the relevant files including action, reducer, root reducer, configStore, Index, and Component to find the problem. If anyone can help me troubleshoot why my a ...

Get the file using jQuery ajax post request

Currently, I am attempting to export the data from my web page and download it as an Excel file. However, despite receiving a successful response, the download does not initiate. $.ajax({ type: "POST", url: _url, contentType: 'multi ...

Don't forget to include the line 'import "reflect-metadata"' at the beginning of your entry point for Jest tests

As I work on developing an application using dependency injection with tsyringe, I came across a case where a service receives the repository as a dependency. Here is an example: import { injectable, inject } from 'tsyringe' import IAuthorsRepos ...

Accessing nested values in JavaScript objects can be achieved using JSON

Imagine you have this JavaScript object retrieved from a Firebase query. { "player": { "player:616320": { "skills": { "main": { "attack": 1, "defence": 1 } ...

I'm looking to use JavaScript to dynamically generate multiple tabs based on the selected option in a dropdown menu

I'm reaching out with this question because my search for a clear answer or method has come up empty. Here's what I need help with: I've set up a dropdown titled 'Number of Chassis'. Depending on the selection made in this dropdown ...

eliminating the existing listener directly from EventM

Let's say I need to create an event listener with ghcjs-dom that triggers on a click and then removes itself. I have addListener :: (IsEventTarget t, IsEvent e) => t -> EventName t e -> SaferEventListener t e -> Bool -> IO ...

Sending Grunt Jade configurations to a specific file

I'm currently using grunt-contrib-jade and I'm trying to utilize the pkg.name and pkg.version variables to generate my css file name. Unfortunately, I haven't been able to make this work on my own and would appreciate any assistance. Below i ...

Master the art of sending multiple asynchronous requests simultaneously with suspense in Vue 3

Utilizing <Suspense>, I am handling multiple requests in my child component using the await keyword: await store.dispatch("product/getProduct", route.params.id).then(res => productData.value = res); await store.dispatch("product/get ...

the deactivation of my rollover class is being caused by my float class

With the assistance of a generous contributor on stackoverflow, I was able to overlay different colored CSS boxes onto various images. These boxes could be removed upon mouseover, revealing the images beneath. You can view the code I used on fiddle here. ...

Dynamically populate an HTML table/grid in CRM 9 with data retrieved from JavaScript records

Currently, I am developing an HTML Page within Dynamics CRM 9.0 environment. A Webresource JavaScript has been created and linked to the HTML page. There is a specific function in the JavaScript that retrieves data from the CRM entity using the following c ...

Exploring the power of ES6 map function within React stateless components

I have a React application that fetches an array of objects from an API response. I want to display each object's details in an accordion format. Using the react-accessible accordion library, I created a React Stateless Component to achieve this. Each ...

What is the best way to create a clickable color feature that triggers a function to change the fill of an SVG object when clicked by the user?

I am attempting to create a user-friendly color selection system where users can click on colors that will then be applied to fill an svg object, similar to a digital coloring book for children. I am struggling to figure out how to instruct JavaScript to s ...

Typescript-powered React component for controlling flow in applications

Utilizing a Control flow component in React allows for rendering based on conditions: The component will display its children if the condition evaluates to true, If the condition is false, it will render null or a specified fallback element. Description ...

Error: Unable to access the 'create' property of an undefined value

I'm currently working on a website that utilizes Passport.js for user management. Despite being able to run my server, I encounter an issue when a user tries to submit their signup details which results in the error message "TypeError: Cannot read pro ...

Issue with overlay functionality after updating to jQuery version 1.12.1

Hey there! I'm currently in the process of upgrading my web application system's jQuery to version 1.12.1 and I've run into an issue with the overlay not functioning properly in the new jQuery version. My setup involves using ajax to displ ...