Currently, I am working on writing Jest-enzyme tests for a basic React application using Typescript along with the new React hooks.
The main issue I am facing is with properly simulating the api call made within the useEffect
hook.
Within the useEffect
, the api call is initiated and updates the state "data" using "setData". The data object is then converted into a table with corresponding table cells.
While attempting to tackle this with a mocked api response and enzyme mount, I keep encountering errors prompting me to use act()
for component updates.
I have tried various ways of using act()
but have been unsuccessful. I also attempted replacing axios with fetch and utilized enzyme shallow along with react-test-library's render, but none of these solutions seem to work.
The component:
import axios from 'axios'
import React, { useEffect, useState } from 'react';
interface ISUB {
id: number;
mediaType: {
digital: boolean;
print: boolean;
};
monthlyPayment: {
digital: boolean;
print: boolean;
};
singleIssue: {
digital: boolean;
print: boolean;
};
subscription: {
digital: boolean;
print: boolean;
};
title: string;
}
interface IDATA extends Array<ISUB> {}
const initData: IDATA = [];
const SalesPlanTable = () => {
const [data, setData] = useState(initData);
useEffect(() => {
axios
.get(`/path/to/api`)
.then(res => {
setData(res.data.results);
})
.catch(error => console.log(error));
}, []);
const renderTableRows = () => {
return data.map((i: ISUB, k: number) => (
<tr key={k}>
<td>{i.id}</td>
<td>
{i.title}
</td>
<td>
{i.subscription.print}
{i.mediaType.digital}
</td>
<td>
{i.monthlyPayment.print}
{i.monthlyPayment.digital}
</td>
<td>
{i.singleIssue.print}
{i.singleIssue.digital}
</td>
<td>
<button>Submit</button>
</td>
</tr>
));
};
return (
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>MediaType</th>
<th>MonthlyPayment</th>
<th>SingleIssue</th>
<th/>
</tr>
</thead>
<tbody'>{renderTableRows()}</tbody>
</table>
);
};
export default SalesPlanTable;
The test:
const response = {
data: {
results: [
{
id: 249,
mediaType: {
digital: true,
print: true
},
monthlyPayment: {
digital: true,
print: true
},
singleIssue: {
digital: true,
print: true
},
subscription: {
digital: true,
print: true
},
title: 'ELLE'
}
]
}
};
//after describe
it('should render a proper table data', () => {
const mock = new MockAdapter(axios);
mock.onGet('/path/to/api').reply(200, response.data);
act(() => {
component = mount(<SalesPlanTable />);
})
console.log(component.debug())
});
My expectation was to log the HTML of the table with the rendered table body section. Despite trying different approaches involving async functions and various methods to mock axios
, I only end up seeing the table headers or receiving the message: An update to SalesPlanTable
inside a test was not wrapped in act(...).
After extensive research for a solution with no success, I decided to seek help here.