Examining the disparity between two dates through mocha/chai testing

I am currently utilizing "chai": "^4.2.0" and "mocha": "^6.1.4",.

Upon using assert.equal() to compare two dates, I encounter a discrepancy where the comparison returns false despite the dates appearing the same. Here is an example of the situation:

https://i.sstatic.net/dSnQz.png

Below is the test scenario in question:

  it('check if dates are correctly added', async () => {
let dataArr = [{'rating_date':'6/6/2019','impact_on_price':'Low'}]   
let priceServ = new PriceService()

// Clear all existing records
priceServ.clearPriceTable()

// Add 1 new record
const res = await priceServ.createOrUpdatePrice(dataArr)

// Retrieve all records from the table with a specific action attribute
const tableValues = await priceServ.getPricesByField('rating_date')
assert.equal(tableValues[0].rating_date, new Date(dataArr[0].rating_date));

});

Any guidance or insights on what might be causing this issue would be greatly appreciated.

Thank you in advance for your responses!

Answer №1

The comparison of Date objects using Chai's assert.deepEqual function is accurate.

const { assert } = require('chai')

const a = new Date(0)
const b = new Date(0)
const c = new Date(1)

assert.deepEqual(a, b) // This is valid
assert.deepEqual(b, c) // This will cause an error

It is important to remember that both arguments passed to deepEqual must be Date objects and not other data types like string or number.

Answer №2

Switching things up, consider opting to bring in the expect function instead of using assert. This allows you to take advantage of Chai's deep equality check method .eql(), like so:

  expect.eql(tableValues[0].rating_date, new Date(dataArr[0].rating_date));

This method is my preference because failure messages display plain dates, making troubleshooting a failing test much simpler.

Answer №3

Just a reminder from my previous comment, assert.equal actually checks for strict equality. You might want to consider comparing the timestamps instead:

assert.equal(tableValues[0].rating_date.getTime(), new Date(dataArr[0].rating_date).getTime());

Keep in mind that if the dates don't match up, the error messages can get pretty messy. There are some useful libraries available to help with that.

Answer №4

Discover the chai-datetime plugin here.

How to Require:

const chai = require("chai");
const assert = chai.assert;
chai.use(require("chai"));

How to Import:

import chai, { assert } from "chai";
import chaiDateTime from "chai-datetime";
chai.use(chaiDateTime);
// original
assert.equal(tableValues[0].rating_date, new Date(dataArr[0].rating_date));

// with plugin
// compares only the date portion
assert.equalDate(tableValues[0].rating_date, new Date(dataArr[0].rating_date));
// compares timestamps
assert.equalTime(tableValues[0].rating_date, new Date(dataArr[0].rating_date));

// Additionally!
let date1 = new Date();
let date2 = date1.toISOString();
let date3 = date1.valueOf();
let date4 = date1.getTime();

assert.equalTime(date1, date1);
assert.equalTime(date1, date2);
assert.equalTime(date1, date3);
assert.equalTime(date1, date4);
assert.equalTime(date2, date1);
assert.equalTime(date2, date2);
assert.equalTime(date2, date3);
assert.equalTime(date2, date4);
// and so forth.
// There are also other assertions introduced, like before-, closeTo-, afterOrEqual-, within-, etc.

let date5 = new Date();
assert.afterOrEqual(date5, date1);
assert.closeTo(date5, date2, 5) // delta = within 5 seconds

Note: When testing, I personally prefer comparing timestamps as it simplifies the process. I once encountered an issue while working on a Java API connected to a MSSQL server with a JS frontend. On my local setup, saving birthdates and training dates functioned properly. However, when my supervisor accessed the live development server, every date saved would be shifted back by one day. This was due to the discrepancy in time zones causing the dates to be interpreted differently. To resolve this, I adjusted all dates to noon to ensure the timezone variance was less than twelve hours.

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

Innovative solution for detecting and replacing undefined object properties in Angular 2 with TypeScript

After encountering the issue of core.umd.js:3523 ORIGINAL EXCEPTION: Cannot read property 'fullName' of undefined I realized that the Exception stemmed from a Template trying to access a specific property: {{project.collaborators["0"]["fullN ...

Creating an efficient login system for my website - where do I start?

I've recently started diving into the world of web development, starting with HTML, CSS, and a bit of JavaScript. However, I've hit a roadblock - while I can perform basic styling, I'm struggling to make my projects interactive. My main que ...

Determine whether a click event originated from within a child window

Currently, I am utilizing window.open to initiate a new window in javascript and my goal is to identify clicks made within the child window. Essentially, if a click event occurs in the child window, I aim to modify the parent window accordingly. I have a ...

Generating Javascript code with PHP and handling quotes successfully

After encountering an issue with apostrophes causing errors in my PHP-generated HTML, I found a solution that involved using the addslashes() function. Here is the code snippet: <?php $lines = array(); $lines[] = "I am happy"; $lines[] = "I'm hap ...

What is the best ECMAScript version to select for implementing the TypeScript compiler in an Electron application?

In my Electron 5.0.6 project, I currently have es3 as the default target in my tsconfig.json file. However, I received an error message indicating that I need to upgrade to at least es6 to utilize getter/setter functionality in TypeScript. I am now contem ...

What is the method for keeping the first column of the table fixed in place?

Incorporating jquery EasyUI, I have created a table where I want the first column to remain static while the rest of the columns scroll when the screen size is reduced. Code snippet available here. Is there a way to freeze just the Title1 column? I attem ...

Activate on click using JavaScript

When a link with the class .active is clicked, I want to use a JavaScript function to deactivate any other active links. The structure of the code should be as follows: <ul class="product"> <li><a href="#myanmar" class="active">Mya ...

Implement multiple selection of parameters in React Material UI version 1.0 and handle the onChange

Currently, I am working on implementing React Material UI 1.0.0-beta.34 and encountering an issue with the Select component. My challenge lies in trying to include an extra parameter in the onChange event handler, yet it seems that only the event parameter ...

Harness the power of npm to execute tests across various directories with the help of wildcards

Whenever I execute this command "test": "mocha *.spec.js *.test.js test/*.spec.js test/*.test.js", It functions as expected, running all the test and spec files in the root directory (2) along with any in the test/ directory (2). In total, 4 tests are ex ...

Finding the substring enclosed by two symbols using Javascript

I'm working with a string that contains specific symbols and I need to extract the text between them. Here is an example: http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_se ...

Creating a webpage using webkit technology

As someone new to web development, I am eager to create a website that is user-friendly on both desktops and mobile devices. Recently, I stumbled upon a site with impeccable design and functionality using what appeared to be "screen webkit". I'm curi ...

Javascript files saved as post meta are failing to load on Wordpress pages

I am facing an issue with my site's load time and storing JavaScript for each page. All my attempts to load JavaScript stored as metadata have been unsuccessful. Whenever I try to load the JavaScript, it displays <script> </script> with a ...

Tips for implementing autocomplete functionality in AngularJS input fields

I attempted to integrate code from a website (http://jsfiddle.net/sebmade/swfjT/) into my program, but unfortunately, the output did not match what was expected. I am also looking to implement a search function by camera id. Can anyone provide assistance? ...

Exploring the World of Browserify Submodules

/xyz /abc.js /abcdef.js /index.js When working with node.js, if you use the require statement for a directory (require('xyz')), it will automatically search for an index.js file within that directory and return the exports defined in that ...

Find Discounts Array

Is there a way to determine the Array of Discounts based on the Base Price initially and then calculate them against the Amount After Discount? In the image provided below, we have the Base Price. This base price may include multiple discounts. Each disc ...

How can I resolve a promise that is still pending within the "then" block?

Here is a piece of code that I have written: fetch(`${URL}${PATH}`) .then(res => { const d = res.json(); console.log("The data is: ", d); return d; }) When the code runs, it outputs The data is: Promise { <pending> ...

SQL AJAX Query Form

I have been searching for tutorials on how to create a good form with PHP and AJAX. I tried starting with a code given to me by a friend and managed to send the request successfully. However, it seems like the data I receive is empty. Could you please take ...

Create allowances for specific areas

One of my methods involves the saving of an author using the .findOneAndUpdate function. The structure of AuthorInterface is as follows: export interface AuthorInterface { name: string, bio: string, githubLink: string, ...

JQuery Validation - Implementing real-time validation on button click instead of form submission

I am currently attempting to use JQuery Validation with WebForms/html. I have simplified the HTML code below, displaying only the necessary elements: <input id="txtEmail"/> <input id="txtTicketID"/> <a id="create" href="#">Create a new t ...

Breaking down a div with jQuery - tips and tricks!

I have a question regarding jQuery. Consider the following structure: <div class="page"> <p>Lorem ipsum....</p> <p>Lorem ipsum....</p> ... </div> I want to transform it into this format: <div class="pa ...