【问题标题】:React JS Jest Unit Testing SpyOn ComponentDidMount action call, Getting Cannot spy on .. property because it is not a functionReact JS Jest 单元测试 SpyOn ComponentDidMount 操作调用,获取无法监视 .. 属性,因为它不是函数
【发布时间】:2020-09-14 15:23:03
【问题描述】:

我正在学习从 componentDidMount() 方法中开玩笑测试反应 js 回流动作调用

jsx 像这样导入 store 调用

import MyStore from '~/stores/myStore'

componentDidMount() {
  MyStore.getData()
}

在我的 myStore.test.jsx 代码中

import React from 'react'
import renderer from 'react-test-renderer'

jest.dontMock('./myStore.jsx')

const MyStore = require('./myStore.jsx').default

describe('', () => {
   it(''), () => {
     const spy = jest.spyOn(MyStore.prototype, 'MyStore.getData')
     render.create(<MyStore/>).getInstance()
     expect(spy).toHaveBeenCalled()
   }
}

我在关注另一个类似的帖子

https://stackoverflow.com/questions/43245040/using-jest-to-spy-on-method-call-in-componentdidmount

但我收到以下开玩笑测试错误

Cannot spy the MyStore.getData() property because it is not a function

我无法找到涉及致电商店的回流操作测试。

有解决办法吗?有没有更好的方法来测试 componentDidMount 中的调用?

谢谢

【问题讨论】:

    标签: reactjs jestjs


    【解决方案1】:

    假设getDataprototype上的一个方法,你应该使用:

    const spy = jest.spyOn(MyStore.prototype, 'getData')
    

    如果你想监视prototype 上的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-09
      • 1970-01-01
      • 2022-01-06
      • 2021-08-21
      • 2020-04-08
      • 1970-01-01
      • 2017-11-29
      相关资源
      最近更新 更多