I have React hooks component, which uses a Material table to render data. And the data is being fetched from the server. I need to test the component to see if the table has data by mocking the Api call. Below is the current code.
dataPopulate.js --
import React, { useEffect, useState, useRef } from 'react';
import MaterialTable from 'material-table';
const dataPopulate = () => {
const [tableLoaded, setTableLoaded] = useState(false)
const tableRef = useRef()
// will try to mock the below function in enzyme jest. But not able to. :(
const data = (query) =>
new Promise(resolve, reject) => {
axios.post('https://datastoremock/getdata')
.then(response => {
const result = []
response.data.forEach(record =>
result.push({
recordKey: record[0],
instId: record[1]
})
)
})
}
return (
<Grid>
<MaterialTable data={data} columns={...hasSomething} tableRef={tableRef}/>
</Grid>
)
}
export default dataPopulate
I tried testing the above by mocking the function data but it doesn't seem to work.
import DataPopulate from './dataPopulate'
import { mount } from 'enzyme'
const spy=jest.spyOn(DataPopulate, 'data') // I get a error here saying 'cannot spy on data property as it is not a function; undefined given instead
spy.mockReturnValue(JSON.parse(`[{'recordKey':'2','instId':'4'}]`))
describe('Table check', () => {
let component = mount(<DataPopulate/>)
})
When I try mocking using jest.spyOn, I get an error saying that 'data' is not a function and the value is undefined. Not sure why, as data is a function in the 'dataPopulate' component which fetches details from the server. Any idea?