【问题标题】:Jest unit test for datetime passes on local, but fails in Jenkins CICD日期时间的开玩笑单元测试在本地通过,但在 Jenkins CICD 中失败
【发布时间】:2022-02-14 08:28:16
【问题描述】:

我正在使用 date-fns 将一些类似日期的字符串解析为日期,然后再解析为字符串,就像这样。我的本地单元测试通过了,但在 Jenkins CICD 中,我的单元测试失败了。我很确定这是由于 Jenkins 机器在 GMT+0 中,而我在 GMT+8 时区。 Jenkins 中失败的测试结果支持了这一点,因为接收到的值比预期值晚了 8 小时。

import { format } from 'date-fns';

function stringToTime(date: string) {
    const newDate = new Date(date);
    return format(newDate, 'k:mm'); // this returns a string
}

还有我的单元测试:

const sampleText = 'Mon Aug 02 2021 22:00:15 GMT+0800';
const expectedText = '22:00';
expect(stringToTime(sampleText)).toEqual(expectedText); // this passes locally

在我的 Jenkins CICD 中,我收到了 14:00。这是一个常见问题吗?有什么快速的方法可以修复我的单元测试以便它可以传递给 Jenkins?

【问题讨论】:

  • 如果这是一个常见问题,我不能说。但是,我也面临 Jenkins 中的日期时间问题。对于您的用例,我将在 jenkins 上的 docker 容器内运行测试。
  • 鉴于时间戳有一个偏移量,它应该在两种环境中被解析为完全相同的时间值,但从 format 返回的时间将是本地时间。因此,如果环境具有与时间戳相同的偏移量(即 +8),则格式化时间仅为 22:00。

标签: javascript unit-testing datetime jenkins jestjs


【解决方案1】:

在传入时间字符串时,我一直在使用 Date 构造函数时遇到问题。尝试使用date-fns 中的parseISO,比如parseISO(date),而不是new Date(date)

另外,您应该从 'date-fns/tmz' 导入以传递时区信息。这样,您可以确保时区是一致的和解析的。这是文档中的一个示例:https://date-fns.org/v2.28.0/docs/Time-Zones

const { zonedTimeToUtc, utcToZonedTime, format } = require('date-fns-tz')

// Set the date to "2018-09-01T16:01:36.386Z"
const utcDate = zonedTimeToUtc('2018-09-01 18:01:36.386', 'Europe/Berlin')

// Obtain a Date instance that will render the equivalent Berlin time for the UTC date
const date = new Date('2018-09-01T16:01:36.386Z')
const timeZone = 'Europe/Berlin'
const zonedDate = utcToZonedTime(date, timeZone)
// zonedDate could be used to initialize a date picker or display the formatted local date/time

// Set the output to "1.9.2018 18:01:36.386 GMT+02:00 (CEST)"
const pattern = 'd.M.yyyy HH:mm:ss.SSS \'GMT\' XXX (z)'
const output = format(zonedDate, pattern, { timeZone: 'Europe/Berlin' })

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 2019-12-07
    • 2018-02-13
    • 2018-07-20
    • 2022-12-05
    • 1970-01-01
    相关资源
    最近更新 更多