TypeError:实用程序不是构造函数

时间:2020-09-09 11:34:51

标签: unit-testing jestjs datetimepicker date-fns muipickersutilsprovider

我正在使用MuiPickersUtilsProvider @material-ui/pickers@中的v-3.2.10

并使用类似以下内容:

import DateFnsUtils from '@date-io/date-fns'
import { DateTimePicker, MuiPickersUtilsProvider } from '@material-ui/pickers'

<MuiPickersUtilsProvider utils={DateFnsUtils}>
                <DateTimePicker .../>
</MuiPickersUtilsProvider>

它可以在UI上运行,但在运行测试用例时会引发如下错误:

TypeError:实用程序不是构造函数

但是,一旦我使用import * as DateFnsUtils from '@date-io/date-fns',我们的测试用例就可以正常工作,但UI上出现相同的错误,

当我使用import {default as DateFnsUtils} from '@date-io/date-fns'时,我们的测试用例可以正常工作,但是两个地方(UI和测试用例)都出现相同的错误

我在下面的链接中找到了类似的讨论,但没有帮助

material-ui-pickers/issues/805

// setup file
var enzyme = require('enzyme');
var Adapter = require('enzyme-adapter-react-16');
require('jest-canvas-mock')
enzyme.configure({ adapter: new Adapter() });

crypto = require('@trust/webcrypto')

// fetch undefined
const fetchPolifill = require('whatwg-fetch')
global.fetch = fetchPolifill.fetch
global.Request = fetchPolifill.Request
global.Headers = fetchPolifill.Headers
global.Response = fetchPolifill.Response

function noOp () { }
if (typeof window.URL.createObjectURL === 'undefined') {
  Object.defineProperty(window.URL, 'createObjectURL', { value: noOp})
}

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,我通过以下代码解决了,

"<MuiPickersUtilsProvider utils={DateFnsUtils}>"


import React, { useState } from 'react'
import DateFnsUtils from '@date-io/date-fns';
import { MuiPickersUtilsProvider, KeyboardDatePicker } from '@material-ui/pickers';

const ProblemStatement = () => {
 const [selectedDate, setSelectedDate] = useState(new Date('2014-08-18T21:11:54'))
    const handleDateChange = (date) => {
        setSelectedDate(date)
    }
    return (
        <div>
            ProblemStatement
            <h2>datepicker</h2>
            //this one
            <MuiPickersUtilsProvider utils={DateFnsUtils}>
                <KeyboardDatePicker
                    margin="normal"
                    id="date-picker-dialog"
                    label="Date picker dialog"
                    format="MM/dd/yyyy"
                    value={selectedDate}
                    onChange={handleDateChange}
                    KeyboardButtonProps={{
                        'aria-label': 'change date',
                    }}
                />
            </MuiPickersUtilsProvider>


        </div>
    )
}