微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

模拟带有TypeScript的forwardRef组件嘲笑mockImplementation

如何解决模拟带有TypeScript的forwardRef组件嘲笑mockImplementation

当组件包装在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...>>>'.

我理解为什么我得到类型错误的原因,因为ocker.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]
      }
    }

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。