Wagner Moreira
Wagner Moreira

Reputation: 1088

React: How to cover dynamic imports in Jest tests?

so I have a react component that uses:

const MyPage = DynamicImport({
  id: 'MyPage',
  loader: () => import('./pages/MyPage/MyPageWrapper'),
});

and jest complains that my test isn't covering the loader, line 22:

enter image description here

then this is used later on the same file:

const tabs = useMemo(
    () => [
      {
        label: 'myPage',
        url: 'myRoute',
        component: MyPage,
      },
      ...

and finally

{tabs.map(({ url, component }) => {
  return <Route path={url} component={component} key={url} />;
})}

I am learning how to write unit tests and I have no clue how to cover this piece in red lines on the screenshot, I've been obviously googling and searching for an answer but I couldn't find anything useful.

This is my test file:

import React from 'react';
import { MyComponent } from '../MyComponent';
import { makeSetupComponent } from '../../../../test_utils';

const MyPage = () => ({
  id: '',
  loader: jest.fn(),
});

jest.mock('../pages/MyPage/MyPageWrapper', () => {
  return {
    MyPageWrapper: jest.fn(),
  };
});

const defaultProps = {
  ...
  };

const setup = makeSetupComponent({
  props: defaultProps,
  shallow: true,
  component: MyComponent,
});

describe('MyComponent component', () => {
  test('Renders correctly', () => {
    const { component } = setup();
    expect(component.exists()).toBe(true);
  });

  test('render MyPage', () => {
    const { component } = setup({ shallow: false });
    console.log('###DEBUG', component.debug());
    console.log('###MyPage', MyPage);

    const { loader } = MyPage();
    loader();

    expect(MyPage).toBeInstanceOf(Function);
    expect(loader).toHaveBeenCalled();
  });
});

Any help/suggestions/links/courses-that-cover-exactly-this would be highly appreciated

Upvotes: 3

Views: 9128

Answers (1)

Lin Du
Lin Du

Reputation: 102597

Here is the unit test solution:

DynamicImport.ts:

export async function DynamicImport({ id, loader }) {
  console.log('real implementation');
  return loader();
}

MyPageWrapper.ts

export function MyPageWrapper() {
  return 'MyPageWrapper';
}

index.ts:

import { DynamicImport } from './DynamicImport';

export function main() {
  return DynamicImport({
    id: 'MyPage',
    loader: () => import('./MyPageWrapper'),
  });
}

index.test.ts:

import { main } from './';
import { DynamicImport } from './DynamicImport';
import { mocked } from 'ts-jest/utils';

jest.mock('./DynamicImport', () => {
  return {
    DynamicImport: jest.fn(),
  };
});

jest.mock('./MyPageWrapper', () => ({
  __esModule: true,
  default: 'mocked MyPageWrapper',
}));

describe('62161452', () => {
  it('should pass', async () => {
    mocked(DynamicImport).mockImplementationOnce(({ id, loader }) => {
      console.log('mocked implementation');
      return loader();
    });
    const actual = (await main()).default;
    expect(actual).toBe('mocked MyPageWrapper');
    expect(DynamicImport).toBeCalledWith({ id: 'MyPage', loader: expect.any(Function) });
  });
});

unit test result with coverage report:

 PASS  stackoverflow/62161452/index.test.ts (9.149s)
  62161452
    ✓ should pass (32ms)

  console.log
    mocked implementation

      at Object.<anonymous> (stackoverflow/62161452/index.test.ts:19:15)

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

test coverage html reporter: enter image description here

Upvotes: 2

Related Questions