Mock return value for useRef passed as an argument

Viewed 271

I have the following function which takes in React.useRef() as an argument.

Having issues in testing it where I am trying to get the useRef to hold values and be able to removeChild().

When I run the test, I am getting following error.

TypeError: useRef.current.removeChild is not a function

This is cos I am passing an object instead of a useRef hook function during test.

How can I pass in a mocked useRef and be able to pass value and perform the removeChild operation during test?

This is the implementation.

export const postData = (
  useRef, // this useRef is coming from the calling component which is actually React.useRef()
  token,
  id
) => {
  useRef.current.children[0].value = token;
  useRef.current.children[1].value = id;

  [...useRef.current.children].forEach((child) => {
    if (!child.value) {
      useRef.current.removeChild(child);
    }
  });
};

This is the test which fails with above error.

it('should work', () => {
    const formRef = {
      current: {
        action: '',
        submit: jest.fn(),
        children: [
          { value: '', },
          { value: '', },
        ],
      },
    };
    postData(formRef, 'mock_token', 'mock_id');
});

As mentioned, failure due to passing an object instead of useRef during test.

Tried the following test instead to address this.

Following test throws this error.

TypeError: Cannot read property 'children' of undefined

import React, { useRef } from 'react';

jest.mock('react', () => {
  const originReact = jest.requireActual('react');
  return {
    ...originReact,
    useRef: jest.fn(),
  };
});

it('should work', () => {
    const formRef = {
      current: {
        action: '',
        submit: jest.fn(),
        children: [
          { value: '', },
          { value: '', },
        ],
      },
    };

    useRef.mockReturnValueOnce(formRef);
    postData(useRef, 'mock_token', 'mock_id');
});
1 Answers

I did this and worked:

jest.mock("react", () => {
  const originReact = jest.requireActual("react");
  return {
    ...originReact,
    useRef: jest.fn(() => ({ current: {} }));
  };
});

Note the "current" key is added. The error of "Cannot read property 'children' of undefined" is because of the missing key.

Related