javascript - 模拟显示为未定义

标签 javascript reactjs mocking jestjs

嗨,我试图在我的 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/

相关文章:

javascript - nodejs异步并行内部异步每个

reactjs - 'this.setState' 有什么问题

javascript - 在 React.js 中将 Async/Await 与 Axios 一起使用

testing - Spock 测试框架中 Mock/Stub/Spy 的区别

c++ - Google 测试框架中的可复制模拟

javascript - 动态 downloadURL( ) 调用

JavaScript 转换 - 为什么比较 "5"> "300"返回 true?

javascript - 滚动 div 代码

linux - 用于Linux的免费网站线框图工具

javascript - Promised ExpressJs 函数中抛出错误