Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mocking react refs with jest/enzyme?

I start learn app testing and me need to test the function. I have some component:

export class Countries extends React.Component<Props, State> {
  private countriesList: React.RefObject<HTMLDivElement> = React.createRef<
    HTMLDivElement
  >();

  public componentDidMount(): void {
    setTimeout(this.whenCDM, 1);
  }


  public render(): React.ReactNode {
    return (
      <div ref={this.countriesList}>
      </div>
    );
  }

  private whenCDM = (): any => {
    if (this.countriesList.current) {
      this.whenComponentDidMount(
        this.countriesList.current.getBoundingClientRect().top
      );
    }
  };
}

I want to test function named whenCDM, and i don't know how do this right.

like image 430
bpGusar Avatar asked Oct 17 '22 12:10

bpGusar


1 Answers

I finally find the answer. I just did not understand what is the "mock".

Here the answer on my question:

First. Need small refactor the function.

private whenCDM = (countriesList:any): any => {
    if (countriesList.current !== null) {
      this.whenComponentDidMount(
        countriesList.current.getBoundingClientRect().top
      );
    }
};

Then in cDM:

public componentDidMount(): void {
    setTimeout(this.whenCDM(this.countriesList), 1);
}

Then create mock function in test file: i guess, i can set in getBoundingClientRect only top option, but anyway...

// ...code
it("whenCDM", () => {
    const getCountriesListRef = () => {
      return {
        current: {
          getBoundingClientRect: () => {
            return {
              bottom: 624,
              height: 54,
              left: 15,
              right: 360,
              top: 570,
              width: 345,
              x: 15,
              y: 570
            };
          }
        }
      };
    };

    const instance = wrapper.instance();
    expect(instance.whenCDM(getCountriesListRef()));
  });
// ...code
like image 77
bpGusar Avatar answered Oct 21 '22 02:10

bpGusar