Search code examples
unit-testingazure-devopsjestjs

Why testing a date passes in the localhost but fails in the Azure pipeline?


I have this unit test :

import { describe, expect, it } from "@jest/globals"

import { format2APIDate } from "../helpers"

describe("format2APIDate()", () => {
  it("should return a date with the format: YYYY/MM/DD for date with this format YYYY-MM-DD", () => {
    const date = new Date("2024-02-12")

    const formattedDate = format2APIDate(date)

    expect(formattedDate).toBe("2024/02/12")
  })

  it("should return a date with the format: YYYY/MM/DD when a date has this format", () => {
    const date = new Date("Mon Feb 12 2024 00:00:00 GMT+0100 (Central European Standard Time)")

    const formattedDate = format2APIDate(date)

    expect(formattedDate).toBe("2024/02/12")
  })
})

When I run the tests locally:

npm run test.

They are passed.

enter image description here

However, when I merge the changes, the last test fails:

enter image description here

This is format2APIDate:

export const format2APIDate = (date: Date) => {
  // Format the date as "YYYY/MM/DD"
  const formattedDate = new Date(date)
  return `${formattedDate.getFullYear()}/${String(formattedDate.getMonth() + 1).padStart(2, "0")}/${String(formattedDate.getDate()).padStart(2, "0")}`
}


Solution

  • In Azure Pipelines, it uses UTC time (GMT+0) that is 1 hour behind than your time zone. In your test code, the date-time "2024/02/12 00:00:00 GMT+1" will be calculated to be "2024/02/11 23:00:00 GMT+0" (or "2024/02/11 23:00:00 UTC").

    You can try to adjust any of the following things in your test code:

    • Adjust the time zone to be UTC (GMT+0).
    • Adjust the hour of time to be large than 1. For example, 02:00:00.