gpt4 book ai didi

javascript - 模拟显示为未定义

转载 作者:行者123 更新时间:2023-12-01 01:44:21 25 4
gpt4 key购买 nike

嗨,我试图在我的 react 应用程序中对一个函数进行两次测试,据我了解,我的模拟函数正在变成未定义的,我不知道为什么。我对模拟函数的调用与此应用程序中的许多其他测试完全相同,但这两个测试不起作用。

我的测试不工作

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({})
})

我正在尝试测试的功能

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":{}})
}
}

npm 测试的输出

enter image description here

有谁知道如何解决这个问题,这样我的模拟就不会变成未定义的?

最佳答案

expect(...).toHaveBeenCalled 接受模拟函数。您正在传递未定义:

  1. 您使用 wrapper.instance().fetchData = jest.fn() 创建了一个模拟函数
  2. 除非您告诉它,否则 jest.fn() 会创建一个现在返回 undefined 的函数。
  3. 您正在调用 fetchData 并将结果(未定义)传递给 Expect 函数。

您需要更改:

expect(wrapper.instance().fetchData()).toHaveBeenCalledTimes(1)

致:

expect(wrapper.instance().fetchData).toHaveBeenCalledTimes(1)

并对您的其他测试进行类似的更改

关于javascript - 模拟显示为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52087331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com