With jest, I want to check if the function is called and if the dispatch method is called in my functional component. I can't make the spy function because it is a functional component and I don't have access to the instance object.
import React, { Component } from 'react';
import { useDispatch } from 'react-redux';
import styles from './style.module.scss';
const AddTask = () => {
const dispatch = useDispatch();
const handleKeyDown = (e) => {
const trimmedText = e.target.value.trim();
if (e.which === 13 && trimmedText) {
dispatch({ type: 'todoAdd', payload: trimmedText });
e.target.value = '';
}
};
return (
<div className={styles.container}>
<span className={styles.arrow} />
<input
className='new-todo'
placeholder='What needs to be done?'
onKeyDown={handleKeyDown}
/>
</div>
);
};
export default AddTask;
import { shallow } from 'enzyme';
import React from 'react';
import { useDispatch } from 'react-redux';
import AddTask from './AddTask';
jest.mock('react-redux');
let wrapper;
describe('Task:', () => {
beforeEach(() => {
wrapper = shallow(<AddTask />);
});
it('snapshot', () => {
expect(wrapper).toMatchSnapshot();
});
it('called dispatch', () => {
expect(useDispatch).toBeCalled(0);
});
it('called handleKeyDown fn', () => {
wrapper.find('input').props().onKeyDown({ key: 'Enter' });
const onKeyDown = jest.fn();
expect(onKeyDown).toBeCalled();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Read more here: https://stackoverflow.com/questions/66328381/how-to-make-a-substitute-function-in-a-functional-component-jest-enzyme
Content Attribution
This content was originally published by Vadim Chesh at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.