如何在 class less 组件上使用 spyOn

how to use spyOn on a class less component

我正在尝试应用 spyOn 来检查我的函数 download 是否在鼠标单击时被调用,但我收到了错误。我已经在关注 但仍然没有线索。谁能告诉我哪里出错了。我想不出任何线索。

错误

Argument of type '"download"' is not assignable to parameter of type '"context"'.
mcb = jest.spyOn(fileDownlaod.instance(), "download");

我的反应组件是:


const Filer = ({Filey} ) => {

const download = () => {
    Filey()
      .then((res: Response) => res.blob())
      .then((data: Blob) => {
        const URL = URL.createObjectURL(data);
      });
  };

  return (
    <>
      <button
        onMouseOver={() => download()}
        onClick={() => download()}
      >
      </button>

    </>
  );
};

export default Filer;

我的笑话测试是:

import React from 'react';
import Filer from './Filer';
import { mount, ReactWrapper } from 'enzyme';
let filer: ReactWrapper<any>;

describe('Filer', () => {
    it('clicked download', () => {
        filer = mount(
            <Filer />
        );
        const _download = () => {
            //some thing
        }

        mcb = jest.spyOn(filer.instance(), "download").mockImplementation(_download);
        filer.find('button').simulate('click')
        expect(mcb.mock.calls.length).toEqual(1);
    });
});

如果您查看了您已经在关注的答案。最后它提到 spyOn 不适用于功能组件内部功能。 这是已经说过的:

Keep in mind that any methods scoped within your functional component are not available for spying

所以你可以窥探传递的道具。

所以应该有效的正确实现可以是:

 it('clicked download', () => {

Filey = jest.fn().mockImplementation(_Filey)

 filer = mount(
            <Filer Filey={Filey}/>
        );
    expect(Filey).toHaveBeenCalled();

});