最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mocking dayjs with Jest - Stack Overflow

programmeradmin4浏览0评论

I'm new to test driven development, I'm trying to implement my simple testing but jest always finds my dayjs as not a function. Also i'm not using typescrcipt so my problem would be similar to this.

I can't seem to find how to setup my jest environment to recognise it as not default export.

Here's my simple test with failed mocking?:

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 />);
  });
});

Error:

 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)

Failed ponent (which actually renders in chrome):

 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]);

I'm new to test driven development, I'm trying to implement my simple testing but jest always finds my dayjs as not a function. Also i'm not using typescrcipt so my problem would be similar to this.

I can't seem to find how to setup my jest environment to recognise it as not default export.

Here's my simple test with failed mocking?:

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 />);
  });
});

Error:

 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)

Failed ponent (which actually renders in chrome):

 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]);

Share Improve this question asked Jul 2, 2020 at 7:03 DevBFDevBF 2571 gold badge4 silver badges15 bronze badges 5
  • What do you see when you console.log dayjs ? – Axnyff Commented Jul 2, 2020 at 7:15
  • 1 why are you using * as dayjs in your code ? can't you do import dayjs from 'daysjs'; – Axnyff Commented Jul 2, 2020 at 7:18
  • Because i'm not using typescript.. thus it is not exported as default github./iamkun/dayjs/blob/… Should be pretty similar to momentjs – DevBF Commented Jul 2, 2020 at 23:07
  • It looks as if it's exported as default to me: github./iamkun/dayjs/blob/… – Axnyff Commented Jul 5, 2020 at 17:11
  • 2 You're right. its the other way around, i'm not using typescript so its a default export... Silly mistakes mate! – DevBF Commented Jul 6, 2020 at 0:20
Add a ment  | 

1 Answer 1

Reset to default 12

MockDate works great for this, no intense mocking code required.

https://www.npmjs./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

Remember to clear the mock after your test with: MockDate.reset();

Also for your situation you probably want to use DayJS UTC to avoid unexpected date math results

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

发布评论

评论列表(0)

  1. 暂无评论