用玩笑嘲笑戴吉斯



我是测试驱动开发的新手,我正在尝试实现我的简单测试,但开玩笑总是发现我dayjs不是函数。此外,我没有使用typecrcipt,所以我的问题与此类似。

我似乎找不到如何设置我的开玩笑环境以将其识别为非默认导出。

这是我的简单测试,模拟失败?

import React from "react";
import { shallow } from "enzyme";
import MainDashboardApp from "../MainDashboard";
jest.mock("dayjs", () => {
return () => jest.requireActual("dayjs")("2020-01-01T00:00:00.000Z");
});
describe("Inititate main dashboard", () => {
it("renders without crashing", () => {
┊ shallow(<MainDashboardApp />);
});
});

错误:

FAIL  src/app/main/apps/dashboards/main/__tests__/dashboard.test.js
● Test suite failed to run
TypeError: dayjs is not a function
9 | import { tableData } from "../helpers";
10 |
> 11 | const defaultStart = dayjs().startOf("month").format("YYYY-MM-DD");
|                      ^
12 | const defaultEnd = dayjs().endOf("month").format("YYYY-MM-DD");
13 |
14 | function IncidentList({
at Object.<anonymous> (src/app/main/apps/operations/incidents/IncidentList.js:11:22)
at Object.<anonymous> (src/app/main/apps/index.js:1:1)
at Object.<anonymous> (src/app/main/apps/dashboards/main/MainDashboard.js:22:1)
at Object.<anonymous> (src/app/main/apps/dashboards/main/__tests__/dashboard.test.js:3:1)

失败的组件(实际上以镶边格式呈现(:

import React, { useEffect, useCallback, useState } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import * as incidents from "app/store/ducks/incident.duck";
import MaterialTable, { MTableToolbar } from "material-table";
import { useHistory } from "react-router-dom";
import * as dayjs from "dayjs";
import { DatePicker } from "@material-ui/pickers";
import { tableData } from "../helpers";
const defaultStart = dayjs().startOf("month").format("YYYY-MM-DD");
const defaultEnd = dayjs().endOf("month").format("YYYY-MM-DD");
function IncidentList({
incidentsList,
requestIncidents,
selectedLoc,
startDate,
endDate,
}) {
const history = useHistory();
const [selectedEndDate, handleEndDateChange] = useState(defaultEnd);
const [selectedStartDate, handleStartDateChange] = useState(defaultStart);
// Deps are ok because history constantly updates, and this handleclick does not need
// to be updated as well
const handleClick = useCallback((event, rowData) => {
history.push({
pathname: `/operation/incident-details/${rowData.id}`,
state: { detail: "testing" },
});
}, []);
useEffect(() => {
if (startDate && endDate) {
handleEndDateChange(endDate);
handleStartDateChange(startDate);
}
}, [startDate, endDate]);

MockDate 非常适合此,不需要激烈的模拟代码。

https://www.npmjs.com/package/mockdate

import MockDate from 'mockdate'
import dayjs from 'dayjs'
MockDate.set('2020-01-01')
console.log(dayjs.format())
// >>> 2019-12-31T18:00:00-06:00

请记住在测试后通过以下方式清除模拟:MockDate.reset();

同样对于您的情况,您可能希望使用 DayJS UTC 来避免意外的日期数学结果

https://day.js.org/docs/en/plugin/utc

最新更新