Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

338
Views
Mock return value for useRef passed as an argument

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');
});
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!