jquery - jest 在调用 jquery 选择器的第三方函数上失败

标签 jquery reactjs jestjs

我有一个调用 dataTable() 的 React 组件datatables.js的功能在 jQuery选择器。我也有相应的 jest 测试组件,但是该函数的测试失败并抛出以下错误。

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

Page.js react 组件

import 'datatables.net-se'

class Page extends Component {

  componentDidMount() {

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

Page.test.js jest 组件(在 it block 中测试失败)

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

})

}

最佳答案

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

页面组件

$.fn.dataTable = require('datatables.net')

class Page extends Component {

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

关于jquery - jest 在调用 jquery 选择器的第三方函数上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48776283/

相关文章:

javascript - 在 enzyme 中模拟 history.back()

javascript - 如何使用 Jest 测试节点列表

javascript - 如何使用 jQuery 选择最后一个可见元素?

javascript - 如何连续显示元素,隐藏它们,然后在 jQuery 中重复

reactjs - 尝试从 componentWillMount 中异步调用的返回值设置状态时,未定义文档

reactjs - React-Google-Maps:缩放 +/-, map /卫星图标不可见

javascript - 开 Jest 测试 hasClass() 方法即使为 true 也返回 false

jquery - 滑出 div,使用 .show ignones {position :absolute; bottom:0px;} in chrome & safari, works in firefox

javascript - 第一个 jquery 插件

javascript - 指定需要的环境变量