我有一个调用 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/