'Pipeline test fails because of time difference of local and pipeline environments

I have problem surrounding the difference between pipeline execution and my local environment. I'm intercepting a request using the following command:

cy.intercept(
      {
        method: "GET",
        pathname: env.path,
        query: {
          dateFrom: "2020-12-31T22:00:00.000Z",
          dateTo: "2022-01-01T21:59:59.000Z",
        },
      },
      (req) => {
        expect(req.url).to.include(
          "&dateFrom=2020-12-31T22%3A00%3A00.000Z",
          "Date From included"
        );
        expect(req.url).to.include(
          "&dateTo=2022-01-01T21%3A59%3A59.000Z",
          "Date to included"
        );
      }
    ).as("filterByDates");

Executing it on my local environment is fine, but when I run it in the pipeline there is a problem, because server time is UTC by default, the test always fails, because sent time is not as expected.

Now I'm thinking how to approach this, because the time input is not by me, but by the plugin "datePicker", which always inputs the machine time (server/environment), so the question is what is a good approach towards this issue? (i'm using day.js) Do I convert each time input to UTC ? Do I intercept the request and make it UTC -2 for the request ? Or should I just ignore everything after "T" including hours/minutes/seconds, which I'm highly against.

I'll really be glad if i get responses, thanks in advance.



Solution 1:[1]

Yes you have to convert expected values to TZ in common with test environment.

But the test also has to know what environment it runs in.

var utc = require('dayjs/plugin/utc')
dayjs.extend(utc)

...

cy.intercept(
  ...

  (req) => {

    let expectedDateFrom = "2020-12-31T22:00:00.000Z";
    const isCI = Cypress.env('CI');
    if (isCI) {
      expectedDateFrom = dayjs().utc().format()
    }
    const encodedDateFrom = encodeURI(expectedDateFrom) 

    expect(req.url).to.include(`&dateFrom=${encodedDateFrom}`,"Date From included");

Since you have two dates, maybe a conversion function?

const toEnvFormat = (expected) => {
  const isCI = Cypress.env('CI');
  if (isCI) {
    expected = dayjs().utc().format()
  }
  return expected; 
}

cy.intercept(
  ...

  (req) => {

    const expectedDateFrom = toEnvFormat("2020-12-31T22:00:00.000Z");
    const encodedDateFrom = encodeURI(expectedDateFrom) 

    expect(req.url).to.include(`&dateFrom=${encodedDateFrom}`,"Date From included");

Ref dayjs UTC

Solution 2:[2]

I've found solution to just add the time zone to the package.json in the root folder as so:

"scripts": {
    "start": "TZ=Europe/Sofia npx cypress open",
    "run": "TZ=Europe/Sofia npx cypress run --browser chrome"
},

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fody
Solution 2 Tyler2P