I am trying to mock useContext following this article:
I understand that the best way to test a component that uses useContext is to mock the context itself.
I have implemented a solution that should be the same as the article but when I run my test I always get TypeError: Cannot destructure property
warning` of 'undefined' or 'null'.
const Alert = () => {
> 6 | const { alert } = useContext(AlertContext); // this is where error happens
`
AlertContext.js:
import React, { createContext, useState, useContext } from 'react';
export const AlertContext = createContext();
export const useAlertContext = () => useContext(AlertContext);
const AlertContextProvider = props => {
const [alert, setAlert] = useState({
text: '',
msg: ''
});
const updateAlert = (text, msg) => {
setAlert({
text,
msg
});
};
return (
<AlertContext.Provider value=>
{props.children}
</AlertContext.Provider>
);
};
export default AlertContextProvider;
Alert.js (component):
import React, { useContext } from 'react';
import './Alert.scss';
import { AlertContext } from '../context/AlertContext';
const Alert = () => {
const { alert } = useContext(AlertContext);
return (
<div className='alert'>
<p>{alert.text}</p>
</div>
);
};
export default Alert;
Alert.js(text)
import React from 'react';
import { shallow } from 'enzyme';
import Alert from '../components/Alert';
import * as AlertContext from '../context/AlertContext';
describe('<Alert />', () => {
test('it should mock the context', () => {
const contextValues = { text: 'suca', msg: 'SUCCESS' };
jest
.spyOn(AlertContext, 'useAlertContext')
.mockImplementation(() => contextValues);
const wrapper = shallow(<Alert />);
const element = wrapper.find('.alert');
expect(element.length()).toBe(1);
});
});
Aucun commentaire:
Enregistrer un commentaire