Taras Osyka
Taras Osyka

Reputation: 33

Mocking compound components with Jest

I have a compound component that looks like this:

export const Layout = Object.assign(Main, {
    Top, Content, Center, Left, Right,
})

There is an object assigning Main to some other components so can use dot notation. Below you can see how I am trying to mock it inside the jest.setup.js file:

jest.mock(
    '~/layouts/Layout', () => ({
        __esModule: true,
        default: (props) => {
            return <mock-layout>{props.children}</mock-layout>
        },
    }),
)

Running jest --ci will return an error with the message Cannot read properties of undefined (reading 'Top')

In this topic I found a way to do something like this:

const component = (props) => <layout-mock>{props.children}</layout-mock>;
component.Top = (props) => <layout-mock-top>{props.children}</layout-mock-top>;

jest.mock(
    '~/layouts/Layout', () => ({
        __esModule: true,
        default: component,
    }),
)

But it gives me the same error. How could I mock it properly? Do you have any ideas?

Upvotes: 3

Views: 747

Answers (1)

etf213
etf213

Reputation: 96

You will need to update the variable name to mockVariable for this to work in order to work around the out of scope variables error. Details here: https://jestjs.io/docs/es6-class-mocks#calling-jestmock-with-the-module-factory-parameter

Upvotes: 1

Related Questions