【问题标题】:How can I write tests for specific dates and time zones in Javascript?如何在 Javascript 中为特定日期和时区编写测试?
【发布时间】:2022-12-03 16:34:49
【问题描述】:

I am using Jest for writing my tests.

I would like to write tests for specific dates and time zones. I already found some solutions for this, but they are not exactly what I need.

Dates:

I know that I can use jest.setSystemTime() to write tests for specific dates. The problem is that I am using a custom date object that extends from the built-in date object. For example, if I run:

jest.setSystemTime(new Date(\'2022-10-05\'));
        
console.log(new Date());
console.log(new CustomDate());

new Date() shows the date I set, but new CustomDate() still shows the current moment. Does anyone know how to fix that?

Time zones:

I know that I can set my time zone when I run jest, for example: TZ=\"Australia/Sydney\" yarn test.

I can also set the time zone in the jest.config.js file.

While both these solutions work, I would have to manually change the time zone and run my tests many times.

Is there any way to change the time zone inside the test itself?

  • Why don\'t you just mock CustomDate?

标签: javascript testing jestjs


【解决方案1】:
猜你喜欢
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-20
  • 1970-01-01
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多