Cypress: Conducting Test with Custom Timezone Setting on Windows

My testing environment was set up to run in UTC time zone. I utilized cy.clock() to initialize a date-time in UTC format, which the Web App will then display as the current browser date-time in UTC.

In order to achieve this, I ensured TZ=UTC in my environment variables and executed my tests in Cypress Runner on a Linux machine using TZ=UTC npx cypress open. The displayed date and time on the web app matched the one I set using cy.clock().

However, when attempting the same method on Windows, it did not work as expected. Using TZ=UTC npx cypress open was unsuccessful in Windows; instead, I had to simply use npx cypress open. The time displayed correctly but the date was off by one day. Changing my Windows PC's timezone to UTC resolved the issue, with both the date and time showing as expected.

Is there an alternative solution that does not involve changing the computer's timezone in Windows? This adjustment is unnecessary in Linux.

Interestingly, my tests run smoothly in CI without needing to define TZ before the script. Setting it in the environmental variable in cypress.json proved sufficient.

Could someone provide further insight or suggestions on this matter?

Below is my cypress.json configuration:

{
    "projectId": "blahblahbah",
    "baseUrl": "http://localhost:4200",
    "numTestsKeptInMemory": 10,
    "chromeWebSecurity": false,
    "TZ": "UTC",
    "env": {
        "BASE_URL": "http://localhost:4200",
        "TZ": "UTC"
    },
    "integrationFolder": "cypress/tests/",
    "retries": {
        "runMode": 2,
        "openMode": 0
    },
    "reporter": "cypress-mochawesome-reporter",
    "reporterOptions": {
        "charts": true,
        "reportPageTitle": "XXXX Test",
        "embeddedScreenshots": true,
        "inlineAssets": true,
        "reportDir": "cypress/reports/",
        "timestamp": "mmddyyyy_HHMMss"
    },
    "video": false
}

Answer №1

If you're looking for a workaround in Windows that doesn't involve adjusting your computer clock, consider using WSL2 to run Linux commands in Windows 11. If you don't already have Windows 11, make sure to update it. If your current computer can't support Windows 11, you may need to purchase a new one.

It's important to ensure that you are on Windows 11 Build 22000 before proceeding.

  1. First, install Docker and follow the instructions to set it up successfully, including configuring WSL2. You'll be directed to a Microsoft guide to install WSL 2 and a Linux distro from the Microsoft Store. Make sure to restart your system after this step.

Next, install the necessary drivers for vGPU:

  • Intel GPU driver for WSL
  • AMD GPU driver for WSL
  • NVIDIA GPU driver for WSL

You can find relevant links here.

After completing these steps, open Powershell as an administrator and enter the commands wsl --update followed by wsl --shutdown. Restart your computer for the changes to take effect.


For those wanting to try their luck or increase their chances of success on non-Windows 11 PCs, follow the sub-steps below:

a. Install VcXsrv (Recommended settings: Multiple windows and Start no client)

b. In VSCode, open the project folder and launch a new terminal selecting Ubuntu (WSL) to access the bash shell.

c. Enter the following commands in sequence:

set DISPLAY variable to the IP automatically assigned to WSL2
export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2; exit;}'):0.0
echo $DISPLAY
# expect something like 192.168.64.1:0.0
sudo /etc/init.d/dbus start &> /dev/null
sudo visudo -f /etc/sudoers.d/dbus

Make sure to adjust firewall permissions to allow VcXsrv on domain, private, and public networks, and then restart your computer.

Following these steps, proceed with installing cypress dependencies and npm and nodejs packages as mentioned above.

To test if everything is working properly, use npx cypress open in the bash shell (Ubuntu WSL).

If you encounter any issues, refer to the provided links for more guidance and troubleshooting tips.

Alternatively, you can utilize Git Bash as another simple solution: Launch Git Bash from VSCode and execute TZ=UTC npx cypress open.

Answer №2

In my opinion, an equivalent command in Windows for TZ=UTC npx cypress open would be

set TZ=UTC && npx cypress open
.

Alternatively, you can use cross-env, which allows a single script to be compatible with various operating systems.

// package.json
{
  "scripts": {
    "cy:open": "cross-env TZ=UTC npx cypress open"
  }
}

However, it seems that cross-env can be picky about the shell being used.

Windows Issues
It's important to note that npm uses cmd by default and this doesn't support command substitution. To enable this feature, you will need to modify your .npmrc file to set the script-shell to powershell.

An additional option is run-script-os

For more information, refer to Run different NPM scripts depending on the platform

// package.json
{
  "scripts": {
    "test": "run-script-os",
    "test:win32": "set TZ=UTC && npx cypress open",
    "test:darwin:linux": "TZ=UTC npx cypress open",
  }
}

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 Recursive Facebook Page Data Scraper using Selenium and Node.js

I am trying to iterate through an array of Facebook page IDs and retrieve the code from each event page. However, I am encountering a problem where I only get the code of the last page ID in the array repeated multiple times. For example, if there are 3 ID ...

Issue encountered during npm installation command

Recently diving into nodejs and experimenting with the Visual Studio Code editor. Encountering difficulties in installing packages, with an error message indicating a possible issue related to the proxy. Despite attempting various solutions found online ( ...

Delivering HTML files to construct a basic single page application with Node.js/Express

I am interested in developing a Single Page Application for my website. From my understanding, a SPA involves sending a single HTML file as the entry point to the application. To achieve this, I plan to use Node and Express to serve the main page, and th ...

NodeJS: Implement session refresh mechanism following permission changes made by other users

Utilizing express-session in my NodeJS application for managing sessions, express-mysql-session to store session data in MariaDB, Passport for authentication, and Sequelize for ORM. Encountering an issue where I am unsure how to refresh a user's sess ...

What steps should I take to resolve the issue I am encountering while attempting to install packages using npm

npm ERR! Linux 4.15.0-36-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "create-react-app" npm ERR! node v8.10.0 npm ERR! npm v3.5.2 npm ERR! path /tmp/npm-7054-19e3727d npm ERR! code EROFS npm ERR! errno -30 npm ERR! syscall mkdir n ...

Encountering error message "no such file or directory" while attempting to run lerna bootstrap

Struggling to execute the following command lerna bootstrap --hoist On a project I downloaded from GitHub. The steps are to Download Then run lerna bootstrap --hoist However, every time I try running the lerna bootstrap --hoist command, it fails with an ...

The promise of a MongoDB connection with Node.js returns as 'awaiting fulfillment'

Greetings to all! A few weeks ago, I embarked on the journey of learning javascript, node.js and mongo. As a beginner, I have an interesting task at hand today. My goal is to add a simple document to the mongoDB and perform a conditional check. So here&apo ...

Original: Generic for type guard functionRewritten: Universal

I have successfully created a function that filters a list of two types into two separate lists of unique type using hardcoded types: interface TypeA { kind: 'typeA'; } interface TypeB { kind: 'typeB'; } filterMixedList(mixedList$: ...

Error encountered while trying to install eslint-plugin-react with an incompatible engine

Hello, I am a new React user and I am running into an issue in my terminal after installing eslint-plugin-react and eslint-plugin-react-hooks. npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: '@es-joy/<a href="/cdn-cgi/l/emai ...

Metro ran into a problem when attempting to resolve the `clsx` module. The error was caused by the module having a `main` field that could not be found

I'm facing an issue while trying to utilize react expo with material ui for developing a gym log application. Every time I attempt to implement something from material ui, I encounter an error. My environment includes Windows 11, node.js 18.18.1, and ...

Opting for a .catch over a try/catch block

Instead of using a traditional try/catch to manage errors when initiating requests like the example below: let body; try { const response = await sendRequest( "POST", "/api/AccountApi/RefundGetStatus", JSON.stringify(refundPara ...

Arranging asynchronous functions using async/await in Node.js/JavaScript

When it comes to organizing my code in js/nodejs, I frequently rely on this pattern. (async function(){ let resultOne = await functionOne(); let resultTwo = await functionTwo(); return { resultOne: resultOne, resultTwo: resul ...

How can I retrieve the GET parameters following the "?" in an Express application?

When dealing with queries like this, I am familiar with how to obtain the parameters: app.get('/sample/:id', routes.sample); In such scenarios, I can easily retrieve the parameter using req.params.id (for example, 2 in /sample/2). However, whe ...

Node.js does not recognize the function Product.findByIdAndRemove

router.delete("/:productId", async (req, res) => { try { const productId = req.params.productId; const deletedProduct = await Product.findByIdAndRemove(productId); if (!deletedProduct) { return res.sta ...

Express.js encountering an `ERR_HTTP_HEADERS_SENT` issue with a fresh Mongoose Schema

My Objective Is If data is found using the findOne() function, update the current endpoint with new content. If no data is found, create a new element with the Schema. Issue If there is no data in the database, then the first if statement throws an ERR_H ...

In TypeScript Next.js 14 APP, object literals are limited to declaring existing properties

I encountered an error in my typescript next.js 14 APP. I need assistance resolving this issue, which states: Object literal may only specify known properties, and 'productPackages' does not exist in type '(Without<ProductCreateInput, Pr ...

Discovering the source of an error in Jest: Unveiling the stack trace and cause

I am currently troubleshooting a nodeJS application. I encountered an error where a variable is undefined. When running the code without Jest, the error was clear and easily located: without jest: ➜ server git:(dc/build) ✗ node test/runner.js /Users/ ...

Utilize forRoot to pass configuration data

When using Angular, I encountered a challenge in passing configuration data to a custom library. Within the user's application, they are required to provide config data to my library through the forRoot method: // Importing the custom library import ...

The response of the Typescript Subscription function

I'm struggling with retrieving the subscribe array in NG2. Being new to typescript, I find it difficult to understand how to pass variables between functions and constructors. This is what my code currently looks like: export class RosterPage exten ...

losing track of the requested parameters while working asynchronously with Firestore documents

Today is my first time experimenting with firestore and express. Here is the code snippet I am using: app.post('/api/create', (req, res) => { (async () => { try { console.log(req.body); //the above consle.lo ...