首页 > 解决方案 > 用于返回 React.Fragment 的函数的单元酶测试,该函数从供应商日期选择器中调用

问题描述

我是单元测试的新手,我脑子里转了好几个小时才弄清楚如何为 renderWeekAndDay 函数编写单元测试。这是我的代码:

const renderWeekAndDayNum = (currentMoment: Moment | null): JSX.Element => {
    return (
        <React.Fragment>
            <span className={componentName('weekNumber')}>{currentMoment ? `W${currentMoment.format('WW')}` : ''}</span>
            <span className={componentName('dayNumber')}>{currentMoment ? currentMoment.format('D') : ''}</span>
        </React.Fragment>
    );
};

const SingleDatePicker: React.FC<props> = ({newDate, onSetDate}): React.ReactElement => {
    const [date, setDate] = useState<any>({selectedDate: newDate});

    const onDateChange = (date: Moment | null): void => {
        setDate({selectedDate: date});
    };

    useEffect(() => {
        onSetDate(date);
    }, [date, onSetDate]);

    return (
        <div className={componentName()}>
            <div className={componentName('container')}>
                <VendorSingleDatePicker
                    {...baseProps}
                    date={date.selectedDate as Moment | null}
                    firstDayOfWeek={FIRST_DAY_OF_WEEK}
                    focused={true}
                    renderDayContents={renderWeekAndDayNum}
                    transitionDuration={0}
                    onDateChange={onDateChange}
                    onFocusChange={EMPTY_FUNCTION}
                />
            </div>
        </div>
    );
};

我尝试了多种方法,但只是在这里进行单元测试:

it('should test the function', () => {
        const mockRenderWeekAndDayNum = jest.fn() as jest.MockedFunction<typeof renderWeekAndDayNum>;

        mockRenderWeekAndDayNum.mockImplementation((momentTest) => {
            return <span>{momentTest}</span>;
        });
    });

我确定我错过了一些东西,但我超级卡在这里。

任何帮助将不胜感激!谢谢!

标签: reactjstypescriptunit-testingjestjsenzyme

解决方案


推荐阅读