【问题标题】:jest fails on third party function called on jquery selector玩笑在 jquery 选择器上调用的第三方函数上失败
【发布时间】:2020-08-27 21:17:55
【问题描述】:

我有一个反应组件,它在jQuery 选择器上调用datatables.jsdataTable() 函数。我也有相应的 jest 测试组件,但是,测试失败的函数抛出以下错误。

● components › <Page /> › check props matchs TypeError: (0 , _jquery2.default)(...).dataTable is not a function

Page.js 反应组件

import 'datatables.net-se'

class Page extends Component {

  componentDidMount() {

    $('.table').dataTable()
  }
 }

Page.test.js 玩笑组件(测试在 it 块中失败)

import React from 'react'
import { Provider } from 'react-redux'
import { BrowserRouter } from 'react-router-dom'
import { configure, shallow, mount } from 'enzyme'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'

import 'datatables.net-se'
jest.mock('datatables.net-se', () => ({ dataTable: jest.fn() }))

// Components 
import Page from '../../components/Customers/Page'

// Setups
const middlewares = [thunk] // add your middlewares like `redux-thunk`
const mockStore = configureMockStore(middlewares)

let store, props, component, wrapper

describe("<Page />", function() {  

  beforeEach(()=>{
    const storeStateMock = {
      customers: Customers
    }

    store = mockStore(storeStateMock)

    props = {
      fetchCustomers: jest.fn()
    }

    wrapper = mount(<BrowserRouter><Provider store={store}><Page {...props} /></Provider></BrowserRouter>)
  })

  it('renders connected component', function() { 

    expect(wrapper.find(Page).length).toEqual(1)
  })

})

}

【问题讨论】:

    标签: jquery reactjs jestjs


    【解决方案1】:

    在尝试了各种替代方案后,我通过将 dataTable 函数附加到 jQuery 来通过测试,如下所示。在应用程序方面,这没有任何区别。我可以将dataTable 导入为import 'datatables.net-se'$.fn.dataTable = require('datatables.net'),它在这两种情况下仍然有效。

    页面组件

    $.fn.dataTable = require('datatables.net')
    
    class Page extends Component {
    
      componentDidMount() {    
        $('.table').dataTable()
      }
     }
     
    

    【讨论】:

    • 使用解决方案时,我遇到了错误 DataTables is not a function 但我没有遇到问题 table.buttons() is not a function。你也遇到过吗?
    • @DanielButler 不太记得了,因为我已经有一段时间没有遇到这个错误了。但是,我假设我的问题已经被我放在这里的解决方案解决了。
    【解决方案2】:

    看来你还是需要将挂载的组件附加到jsdom环境中,这样jquery才能找到它。见jquery doesn't work with jsdom/enzyme

    【讨论】:

    • jQuery 是被 jest 发现的,并且使用 jQuery 或没有它的其他组件的测试通过了。问题是 jest 找不到其他需要附加到 jquery 选择器函数的第三方函数。我有一些调整似乎可以解决这个问题,我也会在这里回答。但是,我仍然不确定这是否是解决问题的正确方法。
    • @bir_ham:我也遇到了同样的问题,那你是怎么解决的?
    猜你喜欢
    • 1970-01-01
    • 2015-02-09
    • 2018-12-30
    • 2018-07-20
    • 2017-02-11
    • 2021-12-16
    • 2020-01-02
    • 2018-05-03
    • 2011-05-20
    相关资源
    最近更新 更多