0

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?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Abhishek
  • 155
  • 3
  • 14

2 Answers2

0

It's tricky to test spy on default export, this solution might help https://stackoverflow.com/a/54245672/15197395

  • 1
    this seems to be a COMMENT, not an ANSWER. you can get more reputation points by working thru the Tour page for this site ... [*grin*] – Lee_Dailey Feb 26 '21 at 03:57
-1

First of all, you cannot mock a function defined within a component. The way you try to mock it const spy=jest.spyOn(DataPopulate, 'data') works for methods of a class you import in a component file.

Secondly, you usually want to do async actions (such as POST request) in useEffect hook.

About testing - in such case you would want to mock axios itself - I'm sure you will find many articles for the case, e.g. this one

Emzaw
  • 618
  • 6
  • 11