📜  mock createRef jest react 功能组件 - Javascript (1)

📅  最后修改于: 2023-12-03 14:44:19.769000             🧑  作者: Mango

Mocking createRef in Jest for React Functional Components

When writing tests for React functional components, you may come across scenarios where you need to mock createRef. createRef is a method that creates a reference to a React component or HTML element. It's often used in class components, but can also be used in functional components to access the DOM elements in the component.

In order to mock createRef, you can use Jest's jest.fn() method.

import React from 'react';

const testFunction = () => {
  const elRef = React.createRef(); 
  return elRef.current;
}

describe('createRef', () => {
  test('should mock createRef', () => {
    const mockCreateRef = jest.spyOn(React, 'createRef').mockReturnValueOnce({
      current: null
    });
    const result = testFunction();
    expect(mockCreateRef).toHaveBeenCalled();
    expect(result).toEqual(null);
  });
});

In the example above, we are testing a function that creates a reference to a DOM element using createRef. We want to mock createRef in this test.

We use jest.spyOn() to create a mock function for React.createRef(). We then use mockReturnValueOnce() to specify that the mock function should return an object with a current property equal to null.

We can then call our test function and assert that the mock function was called and that our result is equal to null.

By mocking createRef, we can prevent the test from interacting with the real DOM element and ensure that our test is fully isolated from external dependencies.

Overall, mocking createRef in Jest can help you write more robust tests for your React functional components.