Skip to content

Instantly share code, notes, and snippets.

@IPWright83
Created August 14, 2020 11:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IPWright83/93548e4a8befb2c242a612d2ee649d53 to your computer and use it in GitHub Desktop.
Save IPWright83/93548e4a8befb2c242a612d2ee649d53 to your computer and use it in GitHub Desktop.

mockComponent.js

This is designed as a simple React component mock to be used with Jest, that still presents enough information to be useful in a Snapshot test. It's handy when you either don't want to shallow render, or are unable to.

Usage

To use this mock, insert the following into your test file, to mock the sub-components, substituting out the names:

jest.mock("../MyComponent", () => ({ MyComponent: (props) => mockComponent("MyComponent", props) }));

Output

This will render a string output useful for snapshot testing.

≤MockMyComponent
    name=foo
    emptyProp=null
    complexProp={"name":"This is a Complex Prop","key":"0001"}
/≥
/* eslint-env jest */
import React from 'react';
/**
* Use this to mock a component and test that the correct props are passed to it
* @param {String} componentName The name of the component that is being mocked
* @param {Object} props The set of props that would normally to to the child component being mocked
* @example
* jest.mock('../MyComponent',
* () => ({
* MyComponent: (props) => mockComponent("MyComponent", props)
* }));
* @return {Function} A react render function
*/
const mockComponent = (componentName, props) => {
const getValue = (key) =>
props[key] === null || props[key] === undefined ? null : JSON.stringify(props[key]);
// Stringify all the props so they can be checked in a snapshot
const stringProps = Object.keys(props || {}).map((key) => ({ key, value: getValue(key) }));
const values = [
`≤Mock${componentName}`,
...stringProps.map((kvp) => ` ${kvp.key}=${kvp.value}`),
'/≥',
];
// The following fragment isn't useless, unfortunately eslint isn't
// being clever enough to realise that this is an array mapping
// eslint-disable-next-line react/jsx-no-useless-fragment
return <>{values}</>;
};
export { mockComponent };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment