Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in running jest test with react-testing-library

It's my first time to write tests. I'm writing tests for a ReactJS app wrote with hooks, and testing using Jest and react-testing-library.

Here's my functional component:

const ItemDetails = ({ item }) => {
  const { code } = item;
  const { getBarcode } = useStationContext();

  return (
    <>
      <Button
        type="primary"
        onClick={() => {
          getBarcode(code);
        }}
        style={{ float: 'right' }}
      >
        Print Barcode
      </Button>
      <List
        bordered
        dataSource={formatData(item)}
        renderItem={({ title, value }) => (
          <List.Item>
            <List.Item.Meta
              description={
                <Wrapper>
                  <p>{upperCase(title)}</p>
                  <div>{value}</div>
                </Wrapper>
              }
            />
          </List.Item>
        )}
      />
    </>
  );
};

export default ItemDetails;

and the test file:

import React from 'react';
import { render, cleanup } from 'react-testing-library';
import ItemDetails from '../containers/Items/ItemPage/ItemDetails';

afterEach(cleanup);

describe('formatData()', () => {
  it('Return Details about item', async () => {
    const { getByText, getByTestId, container, asFragment } = render(
      <ItemDetails
        item={{
          id: '296-c-4f-89-18',
          barcode: 'E-6',
        }}
      />,
    );

    global.console = {
      log: jest.fn(getByText, getByTestId, container, asFragment),
    };

    expect(global.console.log).toHaveBeenCalledWith('test');
  });
});

When I run the test I got this error:

TypeError: Cannot read property 'getBarcode' of null

I don't know how can I fix this?

like image 850
Zeyad Etman Avatar asked Dec 06 '25 05:12

Zeyad Etman


1 Answers

The expectations are wrong because console.log isn't called anywhere. Mocking console object like global.console = ... is a bad practice because it persists between tests and can break things that depend on it, including test runner itself.

There's inconsistency with item code key, it was provided as barcode.

Context value is expected to be undefined, unless default value was provided. It should be provided in test.

It likely should be:

const getBarcodeMock = jest.fn();

const { getByText, getByTestId, container, asFragment } = render(
 <StationContext.Provider value={{ getBarcode: getBarcodeMock }}>
  <ItemDetails
    item={{
      id: '296-c-4f-89-18',
      code: 'E-6',
    }}
  />
 </StationContext.Provider>
);

// ...simulate button click...

expect(getBarcodeMock).toBeCalledWith('E-6');
like image 83
Estus Flask Avatar answered Dec 10 '25 02:12

Estus Flask