Home > OS >  How to test this react component with jest?
How to test this react component with jest?

Time:01-15

I have this wrapper component that I am trying to add test coverage to using jest.

I am not sure where to start, it is not actually being used anywhere that I can see but I still need to add coverage.

I was thinking of just a normal snapshot test but I'm not sure if that is the right approach. Any help or ideas would be greatly appreciated.

import React, { Fragment } from 'react'

export const layoutWrap = <P extends object> (
  Wrapper: React.ComponentType<P>
) =>
  class ResponsiveWrap extends React.Component<P> {
    render() {
      return (
        <Fragment>
          <Wrapper {...this.props} />
        </Fragment>
      )
    }
  }

CodePudding user response:

This HOC doesn't do anything, just wrapped with Fragment and passes all props to the Wrapper component.

You can test it with a normal snapshot test or check the wrapper is present and its prop by yourself.

E.g.

index.tsx:

import React, { Fragment } from 'react';

export const layoutWrap = <P extends object>(Wrapper: React.ComponentType<P>) =>
  class ResponsiveWrap extends React.Component<P> {
    render() {
      return (
        <Fragment>
          <Wrapper {...this.props} />
        </Fragment>
      );
    }
  };

index.test.tsx:

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

function Test(props: { span: number }) {
  return <div>span: {props.span}</div>;
}

describe('70703018', () => {
  test('should pass 1', () => {
    const LayoutWrapTest = layoutWrap(Test);
    const wrapper = shallow(<LayoutWrapTest span={8} />);
    expect(wrapper.find(Test).exists()).toBeTruthy();
    expect(wrapper.find(Test).props()).toEqual({ span: 8 });
  });

  test('should pass 2', () => {
    const LayoutWrapTest = layoutWrap(Test);
    const wrapper = shallow(<LayoutWrapTest span={8} />);
    expect(wrapper).toMatchInlineSnapshot(`
      <Fragment>
        <Test
          span={8}
        />
      </Fragment>
    `);
  });
});

Test result:

 PASS  stackoverflow/70703018/index.test.tsx (9.905 s)
  70703018
    ✓ should pass 1 (22 ms)
    ✓ should pass 2 (13 ms)

 › 1 snapshot written.
-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.tsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Snapshot Summary
 › 1 snapshot written from 1 test suite.

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   1 written, 1 total
Time:        11.045 s
  •  Tags:  
  • Related