Test cases to cover the react component using flag in configuration.json

Viewed 384

Have a flag value defined in configuration.json

{
  isFlag: false
 }

React component is using this flag for rending the some piece of HTML code to it.

import React from 'react';
import { Grid } from '@material-ui/core';
import ArrowForwardIosIcon from '@material-ui/icons/ArrowForwardIos';
import * as configData from '../../configuration/config.json';

export const ComponentElement = () =>(
    <Grid>
      <Grid item>
        {'item element'}
      </Grid>
      {configData?.isFlag && (
        <Grid item>
          <ArrowForwardIosIcon />
        </Grid>
      )}
    </Grid>
  );

Am unable to cover the test cases to the flag since we have set the static value to it. Can someone help me in write the test case which covers the conditional check?

1 Answers

You can use jest.doMock(moduleName, factory, options) to mock the config.json file and its content.

E.g.

index.jsx:

import React from 'react';
import * as configData from './config.json';
console.log('configData: ', configData);

export default function ComponentElement() {
  return <div>{configData.isFlag ? 'ArrowForwardIosIcon' : 'others'}</div>;
}

config.json:

{
    "isFlag": false
}

index.test.jsx:

import { shallow } from 'enzyme';
import React from 'react';

describe('68768758', () => {
  let ComponentElement;
  beforeEach(() => {
    jest.resetModules();
  });
  test('should render others', () => {
    ComponentElement = require('.').default;
    const wrapper = shallow(<ComponentElement />);
    expect(wrapper).toMatchInlineSnapshot(`
      <div>
        others
      </div>
    `);
  });

  test('should render icon', () => {
    jest.doMock('./config.json', () => ({ isFlag: true }));
    ComponentElement = require('.').default;
    const wrapper = shallow(<ComponentElement />);
    expect(wrapper).toMatchInlineSnapshot(`
      <div>
        ArrowForwardIosIcon
      </div>
    `);
  });
});

test result:

 PASS  examples/68768758/index.test.jsx (9.092 s)
  68768758
    ✓ should render others (25 ms)
    ✓ should render icon (13 ms)

 › 1 snapshot written.
  console.log
    configData:  { isFlag: [Getter], default: { isFlag: false } }

      at Object.<anonymous> (examples/68768758/index.js:3:9)

  console.log
    configData:  { isFlag: [Getter], default: { isFlag: true } }

      at Object.<anonymous> (examples/68768758/index.js:3:9)

Snapshot Summary
 › 1 snapshot written from 1 test suite.

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   1 written, 1 passed, 2 total
Time:        10.24 s

jest.config.js:

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'enzyme',
  setupFilesAfterEnv: [
    'jest-enzyme'
  ],
  setupFiles: ['./jest.setup.js'],
  testEnvironmentOptions: {
    enzymeAdapter: 'react16',
  },
};

package versions:

"jest": "^26.6.3",
"ts-jest": "^26.4.4",
"jest-enzyme": "^7.1.2",
Related