【问题标题】:mock showing up as undefined模拟显示为未定义
【发布时间】:2026-02-05 00:35:01
【问题描述】:

您好,我试图在我的 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 test 的输出

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

【问题讨论】:

    标签: javascript reactjs mocking jestjs


    【解决方案1】:

    expect(...).toHaveBeenCalled 接受一个模拟函数。你正在传递undefined

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

    你需要改变:

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

    收件人:

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

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

    【讨论】: