简体   繁体   English

如何在 class 更少的组件上使用 spyOn

[英]how to use spyOn on a class less component

I am trying to apply spyOn to check whether my fucntion download is called on mouse click but I am getting the error.我正在尝试应用 spyOn 来检查是否在单击鼠标时调用了我的功能download ,但我收到了错误消息。 I am already follwoing this question but still no leads.我已经在关注这个问题,但仍然没有线索。 Can anyone tell me where I went wrong.谁能告诉我哪里出错了。 I cannot figure out any clue.我想不出任何线索。

Error错误

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

my react component is:我的反应组件是:


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;

my jest test is:我开玩笑的测试是:

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);
    });
});

If you look at the answer you are already following.如果您查看答案,您已经在关注。 In the end it has mentioned that spyOn does not work on functional components inner functions.最后它提到 spyOn 不适用于功能组件内部功能。 This is what has been said:这就是所说的:

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

So you can spy on props passed.所以你可以窥探传递的道具。

So the correct implementation that should work, can be:因此,应该工作的正确实现可以是:

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

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

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

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM