Search code examples
reactjsreact-testing-library

Warning: React does not recognize the `warnKey` prop on a DOM element


I am using testing-library/react for routing unit test below is my code my test cases getting passed but I am getting console error for

React does not recognize the warnKey prop on a DOM element.

Any Idea ? below is my code and error screenshot

import {render, screen} from '@testing-library/react'
import {createMemoryHistory} from 'history'
import React from 'react'
import {Router} from 'react-router-dom'
import '@testing-library/jest-dom/extend-expect'

import AdminPanel from './AdminPanel'

test('full app rendering/navigating',async () => {
  const history = createMemoryHistory()
  
  render(
    <Router history={history}>
      <AdminPanel />
    </Router>,
  )
  let title = await screen.findByText(/Admin Portal/i)
  expect(title).toBeInTheDocument()

}) 

enter image description here


Solution

  • Check Unknown Prop Warning:

    The unknown-prop warning will fire if you attempt to render a DOM element with a prop that is not recognized by React as a legal DOM attribute/property. You should ensure that your DOM elements do not have spurious props floating around.

    You are using a non-standard DOM attribute on a native DOM node, perhaps to represent custom data

    E.g.

    import React from 'react';
    import { render, screen } from '@testing-library/react';
    import '@testing-library/jest-dom/extend-expect';
    
    const MenuItemGroup = (props) => <div {...props}>Admin Portal</div>;
    
    export default function AdminPanel() {
      return (
        <div>
          <MenuItemGroup warnKey={1} className="menu-item-group" />
        </div>
      );
    }
    
    test('full app rendering/navigating', async () => {
      render(<AdminPanel />);
      expect(screen.findByText(/Admin Portal/i)).toBeInTheDocument();
    });
    

    warnKey is not a standard DOM attribute, we pass it directly to the div element, which will trigger the above warning. The solution is to destructure our custom non-standard attributes from props and pass the standard DOM attributes such as className, role, id to the target element through the spread operator.

    For more standard HTML attributes, you can check All Supported HTML Attributes

    const MenuItemGroup = ({ warnKey, ...rest }) => {
      // Use your custom props `warnKey`
      
      // `rest` props are all standard DOM attributes.
      return <div {...rest}>Admin Portal</div>;
    }