Javascript 模拟显示为未定义
嗨,我正试着在我的react应用程序中对一个函数进行两次测试,据我所知,我的模拟函数正在变成一个未定义的函数,我不知道为什么。我调用mock函数的方式与我在这个应用程序中的许多其他测试完全相同,但这两个测试不起作用 我的不工作测试Javascript 模拟显示为未定义,javascript,reactjs,mocking,jestjs,Javascript,Reactjs,Mocking,Jestjs,嗨,我正试着在我的react应用程序中对一个函数进行两次测试,据我所知,我的模拟函数正在变成一个未定义的函数,我不知道为什么。我调用mock函数的方式与我在这个应用程序中的许多其他测试完全相同,但这两个测试不起作用 我的不工作测试 it('inTimeFrame() work', () => { const wrapper = shallow(<Reactpage />) wrapper.instance().fetchData = jest.fn() wrappe
it('inTimeFrame() work', () => {
const wrapper = shallow(<Reactpage />)
wrapper.instance().fetchData = jest.fn()
wrapper.instance().forceUpdate()
wrapper.setState({'Date1':'2018-07-01','Date2':'2018-08-01'})
wrapper.instance().inTimeFrame()
expect(wrapper.instance().fetchData()).toHaveBeenCalledTimes(1)
})
it('inTimeFrame() throw error3', () => {
const wrapper = shallow(<Reactpage />)
wrapper.instance().fetchData = jest.fn()
wrapper.instance().forceUpdate()
wrapper.setState({'Date1':'2016-07-01','Date2':'2018-08-01',
'getJson':[{'1':1},{'2':2}], 'fetching':true})
wrapper.instance().inTimeFrame()
expect(wrapper.instance().fetchData()).not.toHaveBeenCalled()
expect(wrapper.state('error3')).toEqual(true)
expect(wrapper.state('getJson')).toEqual({})
})
it('inTimeFrame()工作',()=>{
常量包装器=浅()
wrapper.instance().fetchData=jest.fn()
wrapper.instance().forceUpdate()
wrapper.setState({'Date1':'2018-07-01','Date2':'2018-08-01'})
wrapper.instance().inTimeFrame()
期望(wrapper.instance().fetchData()).TohaveBeenCalledTime(1)
})
它('inTimeFrame()抛出错误3',()=>{
常量包装器=浅()
wrapper.instance().fetchData=jest.fn()
wrapper.instance().forceUpdate()
包装器.setState({'Date1':'2016-07-01','Date2':'2018-08-01',
'getJson':[{'1':1},{'2':2}],'fetching':true})
wrapper.instance().inTimeFrame()
expect(wrapper.instance().fetchData()).not.toHaveBeenCalled()
expect(wrapper.state('error3')).toEqual(true)
expect(wrapper.state('getJson')).toEqual({})
})
我要测试的功能
inTimeFrame = () => {
var d1 = moment(this.state.Date1, 'YYYY-MM-DD')
var d2 = moment(this.state.Date2, 'YYYY-MM-DD')
var maxBack = moment().subtract(1, 'year')
if ( d1.diff(d2, 'years') <= 1 && d1.isSameOrAfter(maxBack, 'day')){
this.fetchData()
}else{
this.setState({"error3":true, "getJson":{}})
}
}
inTimeFrame=()=>{
变量d1=力矩(this.state.Date1,'YYYY-MM-DD')
变量d2=力矩(this.state.Date2,'YYYY-MM-DD')
var maxBack=moment().减去(1,'年')
如果(d1.diff(d2,'years')expect(…).tohavencalled
接受模拟函数。您正在传递未定义的:
您使用wrapper.instance().fetchData=jest.fn()创建了一个模拟函数
除非您告诉它,jest.fn()
创建一个现在返回undefined
的函数
您正在调用fetchData
,并将结果(undefined
)传递给expect函数
您需要更改:
expect(wrapper.instance().fetchData()).toHaveBeenCalledTimes(1)
致:
并对您的另一个测试进行类似的更改expect(…)。TohaveEncalled
接受模拟函数。您正在通过未定义的:
您使用wrapper.instance().fetchData=jest.fn()创建了一个模拟函数
除非您告诉它,jest.fn()
创建一个现在返回undefined
的函数
您正在调用fetchData
,并将结果(undefined
)传递给expect函数
您需要更改:
expect(wrapper.instance().fetchData()).toHaveBeenCalledTimes(1)
致:
对你的另一个测试做一个类似的改变