barnab21
barnab21

Reputation: 81

How mock a node library in jest

I am stuck at mock one of my React component because of using one translation library call 'react-simple-i18n'

In my React component, i need import one function from this library to use it as below :

import { useI18n } from 'react-simple-i18n/lib/'

const MyComponent = ({ data }) => {
  const { t } = useI18n()

  return( 
    <div>{t('MyComponent.hello') }</div>
  )
}

and if i try to test with Jest (simple snapshot)

import React from 'react'
import { shallow } from 'enzyme'
import MyComponent from './MyComponent'
import { useI18n } from 'react-simple-i18n'

const fakeData = { ... }

jest.mock('react-simple-i18n', () => {
  useI18n: () => { t: 'test' }
})

let wrapper = shallow(<MyComponent data={fakeData}/>)

describe('MyComponent', () => {
  it('should render MyComponent correctly', () => {
    expect(wrapper).toMatchSnapshot();
  })
})

And i get a fail from Jest :

TypeError: Cannot destructure property t of 'undefined' or 'null'.

How can i proprely mock my useI18n function ?

Upvotes: 1

Views: 3807

Answers (1)

Lin Du
Lin Du

Reputation: 102207

You can use jest.mock(moduleName, factory, options) to mock a library.

E.g.

index.jsx:

import { useI18n } from 'react-simple-i18n';
import React from 'react';

const MyComponent = ({ data }) => {
  const { t } = useI18n();
  return <div>{t('MyComponent.hello')}</div>;
};

export default MyComponent;

index.test.jsx:

import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from './';
import { useI18n } from 'react-simple-i18n';

jest.mock(
  'react-simple-i18n',
  () => {
    const mUseI18n = { t: jest.fn().mockReturnValue('test') };
    return {
      useI18n: jest.fn(() => mUseI18n),
    };
  },
  { virtual: true },
);

describe('MyComponent', () => {
  it('should render MyComponent correctly', () => {
    const fakeData = {};
    let wrapper = shallow(<MyComponent data={fakeData} />);
    expect(wrapper.text()).toBe('test');
    expect(useI18n).toBeCalledTimes(1);
    expect(useI18n().t).toBeCalledWith('MyComponent.hello');
  });
});

unit test results with 100% coverage:

 PASS  stackoverflow/61083245/index.test.jsx (8.334s)
  MyComponent
    ✓ should render MyComponent correctly (8ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.jsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.417s

source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61083245

Upvotes: 3

Related Questions