Jest.js 如何使用@testing-library/react更新props

vvppvyoh  于 2023-06-20  发布在  Jest
关注(0)|答案(2)|浏览(173)

我是个新手,从来没有用过jest library(@testing-library)。我只是想知道是否可以在测试代码中更新props。
下面是我的示例tsx代码:

const Dropdown : React.FC<IDropdownProps> = ({initialValue, items, selected, onSelect}) => {
    return (
        <div>
            <div data-testid="test-dropdown">{selected || initialValue}</div>
                <ul>
                    {items.map((el) => {
                        return (
                            <li 
                                key={"a" + el.id} 
                                onClick={onSelect}
                                role="list"
                                >
                                {el.name}
                            </li>
                        )
                    })}
                </ul>
        </div>
    )
}

下面是我的测试代码:

const items = [{id : 1, name : "1"},{id : 2, name : "2"}];
const initialValue = "Select"

test("Testing", () => {
    const onSelectMock = jest.fn();

    expect(screen.getByTestId('test-dropdown')).toHaveTextContent('Select');
    const obj = render(<Dropdown items={items} initialValue={initialValue} onSelect={onSelectMock(items[1])} />);

    fireEvent.click(el[1]);

    expect(screen.getByTestId('test-dropdown')).toHaveTextContent('2');
});

触发事件后,我想更新选定的 prop ,将其更改为“选择”为“2”,这是下拉组件的属性。
如果是错的,请你给我推荐一下测试方法好吗?

2vuwiymt

2vuwiymt1#

您可以使用render调用公开的rerender方法:

const {rerender} = render(<NumberDisplay number={1} />)

// re-render the same component with different props
rerender(<NumberDisplay number={2} />)

您也可以查看测试库文档here

3mpgtkmj

3mpgtkmj2#

你可以检查下面的方法来动态测试你的回调函数。并触发重新渲染

expect(getByTestId('test-dropdown')).toHaveTextContent('2');
const Dropdown = ({ initialValue, items, selected, onSelect }) => {
  return (
    <div>
      <div data-testid='test-dropdown'>{selected || initialValue}</div>
      <ul>
        {items.map((el) => {
          return (
            <li key={'a' + el.id} data-testid={'a' + el.id} onClick={() => onSelect(el.id)} role='list'>
              {el.name}
            </li>
          );
        })}
      </ul>
    </div>
  );
};

const items = [
  { id: 1, name: '1' },
  { id: 2, name: '2' },
];
const initialValue = 'Select';

test('Testing', async () => {
  let selected = undefined;
  const onSelectMock = (value) => {
    selected = value;
  };

  const { rerender, getByTestId } = render(
    <Dropdown
      items={items}
      initialValue={initialValue}
      onSelect={(e) => {
        onSelectMock(e);
      }}
      selected={selected}
    />,
  );

  expect(getByTestId('test-dropdown')).toHaveTextContent('Select');

  fireEvent.click(getByTestId('a2'));

  rerender(
    <Dropdown
      items={items}
      initialValue={initialValue}
      selected={selected}
      onSelect={(e) => {
        onSelectMock(e);
      }}
    />,
  );

  expect(getByTestId('test-dropdown')).toHaveTextContent('2');
});

相关问题