Code
let basicProps = {
inCart: false,
quantity: 0,
min: 1,
max: 10,
productData: mockProductData
};
const mockData = {
inCart: true,
quantity: 1,
min: 1
};
const mockOnAddToCart = jest.fn(async (data, props) => {
const newProps = await mockAxios(data).post()
const updatedProps = { ...props, newProps };
return updatedProps;
});
test('if clicking the "ADD" button, renders the "increment" button',() => {
let newProps;
async function onClickEvent () {
newProps = await mockOnAddToCart();
};
const { getByText, rerender } = render(
<CTAWrapper
{...basicProps}
onAddToCart={onClickEvent}
/>
);
// CLICK ADD BUTTON
fireEvent.click(getByText('Add'));
console.log({...newProps}); // log - {}
// RE-RENDER PRODUCT CARD COUNTER
// rerender(<CTAWrapper {...newProps}/>);
// TEST IF THE INCREMENT BUTTON IS THERE
// expect(getByText('+')).toBeInTheDocument();
});
__mocks__/axios.js
export default function(data) {
return {
get: jest.fn(() => Promise.resolve(data)),
post: jest.fn(() => Promise.resolve(data))
};
}
Problem
This code doesn't seem to work properly. AFAIK, it is because when I fire the onClick event, it runs onClickEvent
asynchronously, which updates the value of newProps
after it's being logged to the console. The value of newProps
is needed to re-render the component for further assertion testing.
Objective
- Want to mock the
onclick
function - The
onclick
function should make a mockaxios
call - The
axios
call should return a promise - The resolved value of that promise should be the data that is passed to the mock
axios
function - The component should re-render with new props
Stack
Any help is much appreciated.
It would be useful to see the code for your components. Judging by your test the problem is that the logic to update
CTAWrapper
lives in its parent component. If you render that component after the asynchronous code is executed the DOM should update accordingly.