0

Is there a way to use jest.mock's in React? For example, say I want to re-use a component (e.g. Storybook) but want to mock an import / implementation detail for that original React component. Is this possible, and if so, how? Thanks!

sampleComponent.js:

import React from 'react';
import sampleFn from './sampleFn';

const SampleComponent = () => <h1>{sampleFn()}</h1>; // expected output: 'Hello World'

export default SampleComponent;

sampleMockComponent.js:

import React from 'react';
import SampleMockComponent from './sampleComponent';

jest.mock('./sampleFn');

const SampleMockComponent = () => <SampleComponent />; // expected output: 'Testing Mock'

sampleFn.js:

export default () => 'Hello World';

__mocks__/sampleFn.js:

export default () => 'Testing Mock';
Jimmy
  • 3,090
  • 12
  • 42
  • 99

1 Answers1

0

If you want to mock for reasons that are not for testing. I would not suggest you use jest mocks.

Go for a dependency injection pattern.

import React from 'react';
import sampleFn from './sampleFn';

// Unless sample is supplied, sampleFn will be used by default
const SampleComponent = () => {
  const { sample = sampleFn } = props;

  return <h1>{sample()}</h1>;
}

export default SampleComponent;
Daniel Duong
  • 1,084
  • 4
  • 11