【问题标题】:Jest unit test with Luxon: how do I mock .setZone('local')用 Luxon 进行单元测试:我如何模拟 .setZone('local')
【发布时间】:2019-11-27 21:34:12
【问题描述】:

我有一个非常简单的日期组件:

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 吗?
  • 成功了!!谢谢!你让我在我的团队中看起来很聪明。我鼓励你把它作为官方回应。我想得到别人的信任!
  • 这里是官方回答:)

标签: reactjs unit-testing jestjs luxon


【解决方案1】:

Settings.defaultZone 应该可以工作。以防我强调:它会影响所有方法,比如DateTime.local()。有人是already confused

作为替代方案,您可以使用 timezone-mocktimezoned-date 模拟原生 Date,我相信这也应该有所帮助。如果出于某种原因您的代码的某些部分与本机 Date 而不是 luxon 的 DateTime 一起使用,那么这种方法会更加一致。

【讨论】:

  • 哦,我花了几个小时试图模拟 DateTime。出于某种原因,模拟链式模块的示例还没有为我工作,所以我很高兴得到你的设置建议。对于其他人,这是我在@skyboyer 回复后的测试:
  • describe('SimpleDateCell', () => { beforeAll(() => { // 这样本地就不会在测试中使用 Settings.defaultZoneName = 'utc'; }); afterAll( () => { // 返回本地的选项 Settings.defaultZoneName = 'local'; }); it('应该匹配快照', () => { const tree = renderer .create( ).toJSON(); expect(tree).toMatchSnapshot(); }); });
猜你喜欢
  • 2018-04-04
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多