I am writing some unit test but having issues writing a test if the form calls the action function on submit. I am using React Hook Form. Without react hook form the test passes so I believe it has something to do with React Hook Form. Test for delete passes too.
I created a quick example of the code below.
I wrapped the expect for Edit test in waitFor and now I’m getting this error that Actions must be plain objects. Before I did this I was just getting the error “Expected mock function to have been called, but it was not called.”
Can someone please advise?
ReduxForm:
import React, { useState, useEffect } from 'react';
import { Button} from '@mui/material';
import styled from 'styled-components';
import { connect } from 'react-redux';
import { getPosts, deletePost, editPost } from '../redux/actions';
import { useForm, useController } from 'react-hook-form';
const ReduxForm = ({posts, getPosts, deletePost, editPost}) => {
const [postInEdit, setPostInEdit] = useState(false);
useEffect(()=> {
getPosts();
}, [])
const handleDeletePost = async id => {
const deleteResponse = await deletePost(id);
if(deleteResponse) {
getPosts();
} else {
console.log('could not delete post');
}
}
const handleEditPost = (post) => {
setPostInEdit(post.id);
}
return (
<StyledFormContainer data-testid='posts'>
{
posts && posts.map(post => (
<div style={{height: '150px'}} id={post.id} key={post.id}>
{
postInEdit === post.id ? (<EditPostForm post={post} editPost={editPost} />) : (<div data-testid='title'>{post.title}</div>)
}
<div style={{height: '50px', marginTop: '20px'}}>
<Button variant='contained' name='deletBtn' onClick={() => handleDeletePost(post.id)}>Delete</Button>
<Button variant='contained' name='editBtn' onClick={() => handleEditPost(post)}>Edit</Button>
</div>
</div>
))
}
</StyledFormContainer>
)
}
const EditPostForm = ({post, editPost}) => {
const { id, title } = post;
const [postTitle, setPostTitle] = useState(title);
const {control, handleSubmit } = useForm();
const handleSavePost = async () => {
const editResponse = await editPost(id, postTitle);
if(editResponse) {
getPosts();
} else {
console.log('could not edit post');
}
}
return (
<form id={`edit-${id}`} onSubmit={handleSubmit(handleSavePost)}>
<input value={postTitle} name="title" onChange={(e) => setPostTitle(e.target.value)} />
<Button variant='contained' name='saveBtn' type='submit'>Save</Button>
</form>
);
}
const StyledFormContainer = styled.div`
display: flex;
flex-direction: column;
max-width: 20rem;
justify-content: center;
align-items: center;
`;
const mapStateToProps = (state) => ({
posts: state.posts.posts
})
const mapDispatchToProps = dispatch => ({
getPosts: () => dispatch(getPosts()),
deletePost: (id) => dispatch(deletePost(id)),
editPost: (id, title) => dispatch(editPost(id, title))
})
export default connect(mapStateToProps, mapDispatchToProps)(ReduxForm);
Actions:
import axios from 'axios';
export const getPosts =
() =>
async dipatch => {
dipatch({ type: 'FETCHING_POSTS' });
try {
const postsResponse = await axios.get('https://jsonplaceholder.typicode.com/posts');
dipatch({type: 'RECEIVED_POSTS', payload: postsResponse.data.slice(0, 10) });
} catch(e) {
dipatch({type: 'FAILED_RECEIVING_POSTS' });
}
}
export const deletePost =
(id) => {
return async dipatch => {
dipatch({ type: 'DELETING_POST' });
try {
await axios.delete(`https://jsonplaceholder.typicode.com/posts/${id}`);
dipatch({type: 'POST_DELETED'});
return { success: true }
} catch(e) {
dipatch({type: 'FAILED_DELETING_POST' });
return { success: false }
}
}
}
export const editPost =
(id, title) => {
return async dipatch => {
dipatch({ type: 'UPDATING_POST' });
try {
await axios.put(`https://jsonplaceholder.typicode.com/posts/${id}`, {title: title});
dipatch({type: 'POST_EDITED'});
return { success: true }
} catch(e) {
dipatch({type: 'FAILED_UPDATING_POST' });
return { success: false }
}
}
}
Tests:
import React from 'react'
import {render, act, fireEvent, screen, waitFor} from '@testing-library/react'
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import ReduxForm from '../../containers/ReduxForm';
import { Provider } from 'react-redux';
import * as ActionsModule from '../../redux/actions';
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares);
const store = mockStore({
posts: {
posts: [
{
id: 1,
title: 'test'
}
]
}
})
describe('Redux Form', () => {
afterEach(()=>{
jest.clearAllMocks();
})
it('test', () => {
const {getByTestId, container} = render(<Provider store={store}><ReduxForm /></Provider>);
expect(getByTestId('title')).toHaveTextContent('test');
})
it('deletePost is called when delete button is clicked', () => {
const deleteSpy = jest.spyOn(ActionsModule, 'deletePost').mockResolvedValue({success: true});
const {getByTestId, getByText, container} = render(<Provider store={store}><ReduxForm /></Provider>);
expect(getByTestId('title')).toHaveTextContent('test');
act(() => {
fireEvent(
getByText('Delete'),
new MouseEvent('click', {
bubbles: true
})
)
});
expect(deleteSpy).toHaveBeenCalled();
})
it('editPost is called when edit button is clicked', async () => {
const editSpy = jest.spyOn(ActionsModule, 'editPost').mockResolvedValue({success: true});
const {getByTestId, getByText, container} = render(<Provider store={store}><ReduxForm /></Provider>);
expect(getByTestId('title')).toHaveTextContent('test');
fireEvent(
getByText('Edit'),
new MouseEvent('click', {
bubbles: true
})
)
fireEvent(
getByText('Save'),
new MouseEvent('click', {
bubbles: true
})
)
screen.debug();
await waitFor(() => expect(editSpy).toHaveBeenCalled());
})
})
