与 Luxon 的开玩笑单元测试:我如何模拟 .setZone('local')
Jest unit test with Luxon: how do I mock .setZone('local')
我有一个非常简单的日期组件:
import { DateTime } from 'luxon';
export const SimpleDateCell = ({ item, itemKey }) => {
const isoDateString = item[itemKey];
if (!isoDateString) {
return null;
}
const formattedDate = DateTime
.fromISO(isoDateString, { zone: 'utc' })
.setZone('local')
.toLocaleString(DateTime.DATETIME_MED);
return (
<time dateTime={isoDateString} title={isoDateString}>
{formattedDate}
</time>
); };
我只是在本地测试它:
import React from 'react';
import SimpleDateCell from './SimpleDateCell';
import { DateTime, Settings } from 'luxon';
import renderer from 'react-test-renderer';
const testData = {
companyName: 'test company',
tenantId: 'ai/prod/00DA0000000XoMwMAK',
// this will be different on different servers when .setZone('local')
createdDate: '2019-02-13T15:53:00', };
describe('SimpleDateCell', () => {
it('should match the snapshot', () => {
const tree = renderer
.create(
<SimpleDateCell item={testData} itemKey="createdDate" />
).toJSON();
expect(tree).toMatchSnapshot();
}); });
问题是单元测试必须 运行 在我制作快照的同一时区。所以我们的 CI 服务器拒绝了这个。
有没有办法让这个在任何时区都通过? 也许模拟 setZone('local') 响应?有 CI 专家使用 luxon 吗?
谢谢!
Settings.defaultZone
should work. Just in case I highlight: it affects all methods say DateTime.local()
. Somebody was already confused 那个。
作为替代方案,您可以使用 timezone-mock
or timezoned-date
模拟本机 Date
,我认为这也应该有所帮助。如果出于任何原因您的代码的某些部分适用于本机 Date
而不是 luxon 的 DateTime
.
,那么该方法将更加一致
我有一个非常简单的日期组件:
import { DateTime } from 'luxon';
export const SimpleDateCell = ({ item, itemKey }) => {
const isoDateString = item[itemKey];
if (!isoDateString) {
return null;
}
const formattedDate = DateTime
.fromISO(isoDateString, { zone: 'utc' })
.setZone('local')
.toLocaleString(DateTime.DATETIME_MED);
return (
<time dateTime={isoDateString} title={isoDateString}>
{formattedDate}
</time>
); };
我只是在本地测试它:
import React from 'react';
import SimpleDateCell from './SimpleDateCell';
import { DateTime, Settings } from 'luxon';
import renderer from 'react-test-renderer';
const testData = {
companyName: 'test company',
tenantId: 'ai/prod/00DA0000000XoMwMAK',
// this will be different on different servers when .setZone('local')
createdDate: '2019-02-13T15:53:00', };
describe('SimpleDateCell', () => {
it('should match the snapshot', () => {
const tree = renderer
.create(
<SimpleDateCell item={testData} itemKey="createdDate" />
).toJSON();
expect(tree).toMatchSnapshot();
}); });
问题是单元测试必须 运行 在我制作快照的同一时区。所以我们的 CI 服务器拒绝了这个。
有没有办法让这个在任何时区都通过? 也许模拟 setZone('local') 响应?有 CI 专家使用 luxon 吗?
谢谢!
Settings.defaultZone
should work. Just in case I highlight: it affects all methods say DateTime.local()
. Somebody was already confused 那个。
作为替代方案,您可以使用 timezone-mock
or timezoned-date
模拟本机 Date
,我认为这也应该有所帮助。如果出于任何原因您的代码的某些部分适用于本机 Date
而不是 luxon 的 DateTime
.