0
votes

enter image description here

How do I test my component that uses jest and Enzyme with shallow and a react component that uses useContext hook.

How do I mock "pValue.state.fullLang"?

src\LanguageSelect.tsx

import React, { useContext } from 'react';
import { LanguageContext } from './utils/LanguageHook';


function LanguageSelect() {
    const pValue: any = useContext(LanguageContext);

    return (
        <div className="LanguageSelect" data-test="languageSelect-box">
            <div className="languageArea">{pValue.state.fullLang}</div>
        </div>
    );
}

export default LanguageSelect;

src\LanguageSelect.test.tsx

import React from 'react';
import { shallow } from 'enzyme';
import LanguageSelect from './LanguageSelect';

test.only('that the LanguageSelect component exists', () => {

    jest.mock('react', () => {
        const ActualReact = require.requireActual('react');
        return {
          ...ActualReact,
          useContext: () => ({ state: { fullLang: 'mocked context' } }),
      };
    });
    const wrapper = shallow(<LanguageSelect />)

    expect(wrapper.find('[data-test="languageSelect-box"]').exists()).toBeTruthy()
    wrapper.unmount();
})
1

1 Answers

1
votes

If you are testing that component in isolation then you can mock useContext like this:

jest.mock('react', () => {
    const ActualReact = require.requireActual('react');
    return {
      ...ActualReact,
      useContext: () => ({ state: { fullLang: 'mocked context' } }),
  };
});