【问题标题】:Mock forwardRef components jest mockImplementation with typescript使用 typescript 模拟 forwardRef 组件 jest mockImplementation
【发布时间】:2021-01-03 12:54:25
【问题描述】:

当组件被包裹在 forwardRef 中时,您打算如何处理测试文件中的模拟组件? mockImplementation 不在方法上,而是在属性渲染上。

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

我看到的打字稿错误是

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...>>>'.

我明白为什么会收到类型错误,因为 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]
      }
    }

【问题讨论】:

    标签: reactjs typescript unit-testing jestjs react-forwardref


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 2018-07-23
      • 2020-03-18
      • 2021-01-13
      相关资源
      最近更新 更多