Skip to content

Instantly share code, notes, and snippets.

@publicJorn
Created November 24, 2021 10:19
Show Gist options
  • Save publicJorn/d40931da933f125cf4af101d8b85f746 to your computer and use it in GitHub Desktop.
Save publicJorn/d40931da933f125cf4af101d8b85f746 to your computer and use it in GitHub Desktop.
jest mockImplementation for react component
// When you have a complex child component which you need to have different implemenations of
// in order to properly test your parent component
import React from 'react'
import { render, screen } from '@testing-library/react'
import '@testing-library/jest-dom'
import ParentComponent from './ParentComponent'
// Workaround so we can add a spy
import * as childComponent from './ChildComponent'
// Not interested in the actual implementation or hard to setup
// eg. because it does data fetching, setting up a complex state, etc
jest.mock('./ChildComponent')
let ChildComponent: jest.SpyInstance
beforeEach(() => {
// Wrap the component in a spy
ChildComponent = jest.spyOn(childComponent, 'default')
})
test('It has has yes', () => {
// Provide the jsx for ChildComponent
ChildComponent.mockImplementation(() => <p data-testid="ChildComponent">yes</p>)
render(<ParentComponent />)
expect(screen.getByTestId('ChildComponent')).toHaveTextContent('yes')
})
test('It has has no', () => {
// Provide the jsx for ChildComponent
ChildComponent.mockImplementation(() => <p data-testid="ChildComponent">no</p>)
render(<ParentComponent />)
expect(screen.getByTestId('ChildComponent')).toHaveTextContent('no')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment