用Luxon开玩笑的单元测试:我如何模拟.setZone('local')

时间:2019-07-18 22:01:24

标签: reactjs unit-testing jestjs luxon

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

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吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

Settings.defaultZone应该可以工作。以防万一,我强调:它会影响 <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script> $(document).ready(function() { if (window.history && window.history.pushState) { $(window).on('popstate', function() { var hashLocation = location.hash; var hashSplit = hashLocation.split("#!/"); var hashName = hashSplit[1]; if (hashName !== '') { var hash = window.location.hash; if (hash === '') { //alert('Back button was pressed.'); window.location='https://google.com'; return false; } } }); window.history.pushState('forward', null, './#forward'); } }); </script> 这样的所有方法。有人为此already confused

作为替代方案,您可以使用timezone-mocktimezoned-date来模拟本地DateTime.local(),我认为这也可以提供帮助。如果由于某种原因您的代码的某些部分与本机Date而不是luxon的Date一起使用,则该方法将更加一致。