reactjstypescriptjestjsspyon

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

Solution

  • 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. 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();
    
    });