Simulate a new Date object in Deno for testing purposes

Has anyone successfully implemented something similar to

jest.spyOn(global, 'Date').mockImplementation(() => now);
in Deno?

I've searched through the Deno documentation for mock functionality available at this link, as well as explored the mock time feature detailed here. However, it doesn't seem like either of these options will effectively replace the new Date() with the desired mocked implementation.

Answer №1

You have the ability to directly override any global variable - they can be accessed as properties/methods on globalThis.

For example, here's a demonstration (not specific to any particular testing framework) that swaps out the global Date class with a custom class containing a method called toString:

class CustomClass {
  toString() {
    return "Just an illustration";
  }
}

function replaceDateAndRetrieveOriginalFn() {
  const originalDate = globalThis.Date;
  globalThis.Date = CustomClass;
  return () => void (globalThis.Date = originalDate);
}

console.log(new Date().toString()); //=> <A string representing the current date>

const restore = replaceDateAndRetrieveOriginalFn();
console.log(new Date().toString()); //=> "Just an illustration"

restore();
console.log(new Date().toString()); //=> <A string representing the current date>

Answer №2

If you want to mimic the behavior of new Date in Deno, one way to do it is by using @sinonjs/fake-timers

import FakeTimers from "npm:@sinonjs/fake-timers";
import { assertEquals, assertNotEquals } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2818696b2c2dcc3cbc2dcc2">[email protected]</a>/testing/asserts.ts";

Deno.test("New Year", () => {
  const clock = FakeTimers.install();
  clock.setSystemTime(new Date('2020-01-01'));

  // Celebrating New Year
  assertEquals(new Date().toDateString(), 'Wed Jan 01 2020');
  clock.uninstall();
});

Deno.test("now", () => {
  // Not yet New Year
  assertNotEquals(new Date().toDateString(), 'Wed Jan 01 2020');
});

For those already using jest, you can opt for jest.useFakeTimers() along with

.setSystemTime(now?: number | Date)

jest
  .useFakeTimers()
  .setSystemTime(new Date('2020-01-01'));

Remember to switch back to real timers when finished by calling jest.useRealTimers()

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

Leveraging Angular to incorporate HTML templates from one component into another component

I am currently working with two components. The first one is a table component, identified by the selector 'table-component', which has standard filtering capabilities. The second component is designed for displaying the table on a page. This me ...

Issue: The module "node:util" could not be located while attempting to utilize the "sharp" tool

Upon adding sharp to my Node.js application and attempting to use it, I encountered the following error: /Users/username/Documents/GitHub/Synto-BE/node_modules/sharp/lib/constructor.js:1 Error: Cannot find module 'node:util' Require stack: - /Use ...

Looking to seamlessly integrate a CommonJS library into your ES Module project while maintaining TypeScript compatibility?

I am interested in creating a project with Typescript. The project is built on top of the Typescript compiler, so I am utilizing Typescript as a library, which I believe is a CommonJS library. Although the project is designed to run on Node (not in the bro ...

Dynamic form name validation in Angular is crucial for ensuring the accuracy and

When it comes to validating a form in Angular, I usually use the ng-submit directive like this: <form name="formName" ng-submit="formName.$valid && submitForm()"></form> This method works well for forms with predefined names that I se ...

The component triggering the redirect prematurely, interrupting the completion of useEffect

I set up a useEffect to fetch data from an endpoint, and based on the response, I want to decide whether to display my component or redirect to another page. The problem I'm facing is that the code continues to run before my useEffect completes, lead ...

Decorators are not allowed in this context, the Angular component constructor may not include them

Currently working on developing a dialog component in Angular 17 using Angular Material 17 Encountering an issue inside the constructor of the dialog component where utilizing the @Inject decorator as shown in the official documentation example is not pos ...

Incorrect date format sent to backend through API

Within my Angular + Angular Material application, I am facing an issue with a date range picker. My goal is to send the selected start and end dates in a formatted manner through an API call. However, when the date values are sent over the API as part of t ...

The AJAX data variable fails to send to PHP script although $_POST is defined

I am at my wit's end with this problem. I am attempting to send a variable to a PHP script using AJAX, and although I can confirm that $_POST is set, the variable remains undefined. Oddly enough, I have used almost the same code in other instances an ...

In Vue, the CropperJs image initially appears small, but it returns to its original size after editing

I encountered a peculiar issue while working on a website for image cropping using Vue.js and CropperJs. On the homepage, users can select an image to crop and proceed to the next page where a component named ImageCropper.vue is displayed. Strangely, the c ...

Forming a distinct array from a collection of objects

Describing demoList: demoList = [ { id: 1, validFrom: "2019-06-01T00:00:00", validTo: "2020-06-17T00:00:00", xxxM: 50, xxxN: 2.2, xxxQ45: 2, xxxQ100: 1.65, xxxQ125: null, xxxQ150: null, xxxQ2 ...

ReactJS and Redux: setting input value using properties

I am utilizing a controlled text field to monitor value changes and enforce case sensitivity for the input. In order to achieve this, I need to access the value property of the component's state. The challenge arises when I try to update this field ...

The mat-table's data source is failing to refresh and display the latest

When I click on a column header to sort the table, a function should trigger and update the data. However, the data is not updating as expected. Below is the code for the function and the table: <table mat-table #table [dataSource]="dataSourceMD&qu ...

What are the consequences of altering the DOM in React?

As a beginner react developer, I am currently working on creating a MERN App. I have a question for the community regarding my project where I needed to make several changes to the DOM as illustrated below: document.getElementsByTagName('body')[ ...

Attempting to retrieve nested data, only to be met with an undefined response

I've been attempting to retrieve specific information by iterating through the SearchResult object like so: for (let productKey in SearchResult) { if (SearchResult.hasOwnProperty(productKey)) { products.push({ name ...

Utilize Javascript or Jquery to intercept and handle both GET and POST requests

Is there a method to effectively intercept and capture both GET and POST requests as they are sent from the browser to the server? In my web application, full page refreshes occur after each request is submitted, however, some pages experience delays in r ...

What rules should be followed in Python when it comes to using nested parentheses in functions?

Currently in the process of deleting my account from this platform, I am intentionally adding unnecessary content to this post. Please refrain from restoring the previous content. - Original Poster ...

Experiencing issues with overflowing columns in JQuery Datatables

I am currently facing an issue with my datatable where I need it to have a specific width while also displaying all its columns. The problem I am encountering can be summarized as follows: I came across solutions like Datatables Width Overflow For A ...

Error encountered when attempting to use the submit button in AngularJS

My goal is to create a simple Angular application that takes input of two numbers (n1 and n2) and then prints their sum. I have integrated Bootstrap for styling, but noticed that nothing was happening upon submission. To troubleshoot, I added an alert() fu ...

Creating a scheduled redirect button using JavaScript and another button to cancel it

I'm facing an issue with my code. When the first button is clicked, it redirects the user to a different URL after 10 seconds. However, I'm struggling to make the second button cancel the redirect if pressed before the 10 seconds are up. Despite ...

Simulated web server for testing with Jest

Can I ask a unique question? I have a tool for extracting data from webpages directly, not through APIs. I want to create end-to-end tests for this tool using the Jest library, but I need to ensure the web pages I'm referencing remain consistent. It&a ...