Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react - writting twice same test passes first but not second time

Tags:

reactjs

Im a bit new to the react ecosytem. Im having a weird behaviour with passing tests.

Im using CRA, prop-types and react-test-library.

Here is my component:

import React from 'react';
import PropTypes from 'prop-types';

export default function Navbar({
  Logo, MenuItems, className,
}) {
  return (
    <nav aria-label="navigation bar" className={className}>
      {Logo}
      <div>
        { MenuItems.map((MenuItem) => MenuItem) }
      </div>
    </nav>
  );
}

Navbar.defaultProps = {
  className: '',
};

Navbar.propTypes = {
  className: PropTypes.string,
  Logo: PropTypes.node.isRequired,
  MenuItems: PropTypes.arrayOf(PropTypes.node).isRequired,
};

I want to test that prop-types complains when params are not receiving the right type.

import React from 'react';
import { render } from '@testing-library/react';
import Navbar from './Navbar';

describe('<Navbar />', () => {
  beforeAll(() => {
    jest.spyOn(console, 'error').mockImplementation(() => {});
  });

  beforeEach(() => {
    console.error.mockClear();
  });

  afterAll(() => {
    console.error.mockRestore();
  });

  it('renders', () => {
    render(<Navbar
      Logo={<p data-test="logo">My logo</p>}
      MenuItems={[
        <p key="spanish">Spanish</p>,
        <p key="english">english</p>,
      ]}
    />);

    expect(console.error).not.toHaveBeenCalled();
  });
  it('errors to console when Logo is missing', () => {
    render(<Navbar MenuItems={[
      <p key="spanish">Spanish</p>,
      <p key="english">English</p>,
    ]}
    />);
    expect(console.error).toHaveBeenCalled();
  });

  it('does not error to console when Logo is missing', () => {
    render(<Navbar MenuItems={[
      <p key="spanish">Spanish</p>,
      <p key="english">English</p>,
    ]}
    />);
    expect(console.error).toHaveBeenCalled();
  });
});

My thinking is that Im not resetting properly the mocks, they have some state that it is not clear or something similar.

What am i missing?

like image 784
kitimenpolku Avatar asked Feb 04 '26 06:02

kitimenpolku


1 Answers

PropTypes.checkPropTypes(...) only console.errors a given message once. To reset the error warning cache in tests, call PropTypes.resetWarningCache()

Source

Try invoke resetWarningCache in your beforeEach hooks

import PropTypes from 'prop-types';


beforeEach(() => {
   PropTypes.resetWarningCache()
});
like image 63
lastr2d2 Avatar answered Feb 06 '26 22:02

lastr2d2