Макет компонентов forwardRef, имитирующий реализацию с помощью typescript

#reactjs #typescript #unit-testing #jestjs #react-forwardref

#reactjs #typescript #модульное тестирование #jestjs #реагировать-forwardref

Вопрос:

Как вы предполагаете обрабатывать компоненты-макеты в тестовых файлах, когда компонент завернут в forwardRef? Макет реализации выполняется не в методе, а вместо этого в рендеринге свойства.

 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 */

  

Ошибка typescript, которую я вижу, заключается в

 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"> amp; RefAttributes...>>>'.
  

Я понимаю, почему я получаю ошибку типа как mockComponent.mockImplementation не определено, но как мне правильно определить тип?

Макет выглядит как

 {
      '$$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]
      }
    }
  

Ответ №1:

 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