Mock forwardRef components jest mockImplementation with typescript
Asked Answered
Q

1

8

How are you suppose to handle mocking components in test files when the Component is wrapped in forwardRef? The mockImplementation is not on method, but instead is on a property render.

import React from 'react';
import Component from './Component';
import mocked from 'ts-jest/utils'

jest.mock('./Component');

const mockComponent(Component);

mockComponent.mockImplementation(() => <></>) /* this returns type error that mockImplementation is not a function */

mockComponent.render.mockImplementation(() => <></>) /* this works but get a typescript error */

The typescript error I see is

TS2339: Property 'render' does not exist on type 'MockedFunction   "li", {}>, "button" | "slot" | "style" | "title" | "className" | "classes" | "innerRef" | "selected" | "dense" | "key" | "value" | "defaultChecked" | ... 261 more ... | "focusVisibleClassName"> & RefAttributes...>>>'.

I understand why I get the type error as mockComponent.mockImplementation is undefined, but how do I get the type correctly inferred?

The mock appears as

{
      '$$typeof': Symbol(react.forward_ref),
      render: [Function: mockConstructor] {
        _isMockFunction: true,
        getMockImplementation: [Function],
        mock: [Getter/Setter],
        mockClear: [Function],
        mockReset: [Function],
        mockRestore: [Function],
        mockReturnValueOnce: [Function],
        mockResolvedValueOnce: [Function],
        mockRejectedValueOnce: [Function],
        mockReturnValue: [Function],
        mockResolvedValue: [Function],
        mockRejectedValue: [Function],
        mockImplementationOnce: [Function],
        mockImplementation: [Function],
        mockReturnThis: [Function],
        mockName: [Function],
        getMockName: [Function]
      }
    }
Quotha answered 16/9, 2020 at 16:27 Comment(0)
P
0
import React from 'react';
// Asuming Component is a default exported component
import * as Component from './Component';

jest.mock('./Component');
const MockComponent = jest.fn(() => <div />);

jest.spyOn(Component.default.type, 'render').mockImplementation(MockLaneMarkup);

//now you can test if the MockComponent has beenCalled
Prudery answered 8/4, 2021 at 11:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.