1

im writing jest file for a feature, and while coming from Angualr jasmine seems very similar to jest. Im encounter some issue while trying to mock some function in the jest file.

const MMycustomContext= React.createContext({});

export const userActionMenuPopUpBuilder = (action, target, id) => {

  const { statePath,breadcrumbers, } = useContext(MMycustomContext);
 
  const [showPopUp, setShowPopUp] = useState(false);
  const [itemSelected, setItemSelected] = useState({});
}

And this is my Jest file:

describe('userActionMenuPopUpBuilder ', () => {

    it('Should be Truthy', () => {

  
    jest.spyOn(React, 'useContext').mockImplementationOnce(() => {
            return {
                name: 'this is a mock context return value'
            }
        })

       const temp = userActionMenuPopUpBuilder (mockAction, target, id);

        console.log(temp);
        expect(temp).toBeTruthy();
    });


});

when im running the Jest file, i get exception because useContext is undefined- calling userActionMenuPopUpBuilder function from the jest file, i tried to spyOn and make a mock from useContext like i did above, but it dosent seems to work and i still gets undefined,

Any suggestions?

thanks

John doe
  • 317
  • 3
  • 5
  • 15
  • I suggest you don't do this. There's a reason you're not finding good resources on mocking hooks and that's because it's bad practice. You should be writing tests around the DOM or mocking external dependencies, not mocking the internal implementation of React – possum Nov 02 '22 at 14:50
  • 1
    As @possum said you shouldn't mock these hooks. Your tests should resemble your real code as much as possible. `userActionMenuPopUpBuilder` seems to be a custom hook you can test it on its own using this [library](https://github.com/testing-library/react-hooks-testing-library) or you can test directly the component calling this custom hook – Renaud Aubert Nov 02 '22 at 14:53
  • Does this answer your question? [How to test react useContext useReducer dispatch in component](https://stackoverflow.com/questions/63142322/how-to-test-react-usecontext-usereducer-dispatch-in-component) – gunwin Nov 02 '22 at 18:03
  • Please provide a https://stackoverflow.com/help/minimal-reproducible-example, the code of `userActionMenuPopUpBuilder` seems not complete. Please provide complete code – Lin Du Nov 04 '22 at 03:32

0 Answers0