1

I'm testing a GridTiles component which will render a Grid component with a certain number of columns.

grid-tiles.tsx:

const GridTiles: FC<GridTilesProps> = ({ columns, tiles, ...props }) => {
  return (
    <Grid templateColumns={`repeat(${columns ?? 1}, 1fr)`} {...props}>
      {tiles.map((tile) => (
        <GridItem>{tile}</GridItem>
      ))}
    </Grid>
  );
};

grid-tiles.test.tsx:

const mockedGrid = Grid as jest.MockedFunction<typeof Grid>;

describe('Grid Tiles', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });
  describe('When passing props with columns', () => {
    it('should render component with correct template columns', () => {
      render(<GridTiles tiles={[]} columns={2} />);

      expect(mockedGrid).toHaveBeenCalledTimes(1);
      expect(mockedGrid).toHaveBeenCalledWith(
        expect.objectContaining({
          templateColumns: 'repeat(2, 1fr)',
        }),
      );
    });
  });
});

Apparently, the Grid is being called only once, but when doing toHaveBeenCalledWith, it shows 2 calls, one with the correct parameters, and the other with a plain {}, which is the one failing.

I don't know why it shows two parameters, when it is being only called once (as I tested on the previous expect.toHaveBeenCalledTimes(1).

The test fails with this message:

enter image description here

Does anyone know why this happens, or how can I solve this?

  • 1
    Please do not post pictures of text when you can post the text itself. – possum Oct 27 '22 at 13:19
  • It's not telling you the mock got called twice (as you say, the previous expectation would have failed if so). The call it shows with the "correct parameters" is the **call you expected**, hence: `Expected:`. It's not being called _twice_, it's being called with _two parameters_ (and you said there should only be one). – jonrsharpe Oct 27 '22 at 13:21
  • If you're comfortable with Chrome's debugger, Jest does have a way to debug its scripts and step through the code: https://jestjs.io/docs/troubleshooting – Leland Oct 27 '22 at 13:21
  • I'll also point out what you are doing is far outside normal React testing prescriptions. It is extremely unusual to mock a component. Tests should be around the presented DOM or external code interactions, not on internal implementations. – possum Oct 27 '22 at 13:22
  • @jonrsharpe How can a react component be called with two parameters? Isn't always a single object parameter with the props? – Leonardo Teixeira Oct 27 '22 at 13:29
  • No, props isn't the only argument. See e.g. https://stackoverflow.com/q/56879095/3001761 – jonrsharpe Oct 27 '22 at 13:31

0 Answers0