Skip to content
Advertisement

React testing mock variable in functional component

Please help. I cannot run test because in my util langProvider is package that drops tests. I have to mock langProvider function or strings variable. How I can do that?

import React, { ReactElement, useState } from 'react';
import langProvider from 'utils/langProvider';

import { HeaderStyled, DropDownStyled } from './styled';
import './style.scss';

function Header(props: any): ReactElement {
  const [state, setState] = useState({
    isDropDownOpened: false,
    isDrawerOpened: false,
  });

  const strings = langProvider(props.language, 'components.header');

  return (
    <HeaderStyled className="header">
      ...
    </HeaderStyled>
  );
}

const mapStateToProps = (state: any) => ({
  language: state.language,
});

export default connect(mapStateToProps)(Header);

My test file

import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import React from 'react';
import Header from './index';

configure({ adapter: new Adapter() });

describe('<Header />', () => {
  const wrapper = shallow(<Header />);

  it('My test', () => {
    expect('').toEqual('Header');
  });
});

Advertisement

Answer

not sure, but you can try to insert in your test file before describe function, something like that:

jest.mock("utils/langProvider", () => ({langProvider: ()=> []}));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement