Home > Mobile >  getById is not a function
getById is not a function

Time:01-07

When I try to simulate a click I am getting the error in the subject line.

My whole test file:

import '@testing-library/jest-dom'

import * as React from 'react';

import TestRenderer, {act} from 'react-test-renderer';
import { fireEvent, render } from "@testing-library/react";
import {jest} from '@jest/globals';

describe('parent component', () => {
    const component = TestRenderer.create(
        <Component/>,
      );
    it('renders correctly', () => {
        let tree = component.toJSON();
        expect(tree).toMatchSnapshot();
    });
    test('my click event', () => {
    const handleClick = jest.fn();
    const { getById } = TestRenderer.create(
        <Component onClick={handleClick}/>,
      );
    const button = getById('component-div-id');
    fireEvent.click(button);
    expect(handleClick).toHaveBeenCalledTimes(1);
    });
});

The error points specifically to the getById:

TypeError: getById is not a function

  28 |         <Component onClick={handleClick}/>,
  29 |       );
> 30 |     const button = getById('component-div-id');

CodePudding user response:

ChatGPT seems to have the answer, this is the correct way of grabbing a component test id and seems to have worked for me:

import { render, getByTestId } from '@testing-library/react';

const { container } = render(<MyComponent />);
const element = getByTestId(container, 'my-element-test-id');

CodePudding user response:

Looks like you're combining two different test libraries, TestRenderer does not have a method called getById, but react testing library does have one that is called getByTestId that will look for an element that has the attribute data-testid.

For example if you have a div like this one:

<div data-testid="component-div-id">A div</div>

Do this

import { fireEvent, render } from "@testing-library/react";

const { getByTestId } = render (
    <Component onClick={handleClick}/>,
);
// Do the assertions
const button = getByTestId('component-div-id');
fireEvent.click(button);

In case you want to look by the actual id attribute like:

<div id="component-div-id">A div</div>

you have to do this:

import { fireEvent, render } from "@testing-library/react";

const component = render (
    <Component onClick={handleClick}/>,
);
// Do the assertions
const button = component.container.querySelector('#component-div-id');
fireEvent.click(button);
  • Related