我如何测试道具是否传递给孩子? [英] How can I test if a prop is passed to child?

查看:55
本文介绍了我如何测试道具是否传递给孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的组件看起来像这样:(它具有更多的功能以及列,但是为了使示例更简单,我没有包括它)

My component looks something like this: (It has more functionality as well as columns, but I have not included that to make the example simpler)

const WeatherReport: FunctionComponent<Props> = ({ cityWeatherCollection, loading, rerender }) => {
  /* some use effects skipped */
  /* some event handlers skipped */

  const columns = React.useMemo(() => [
    {
      header: 'City',
      cell: ({ name, title }: EnhancedCityWeather) => <Link to={`/${name}`} className="city">{title}</Link>
    },
    {
      header: 'Temp',
      cell: ({ temperature }: EnhancedCityWeather) => (
        <div className="temperature">
          <span className="celcius">{`${temperature}°C`}</span>
          <span className="fahrenheit">{` (~${Math.round(temperature * (9 / 5)) + 32}°F)`}</span>
        </div>
      )
    },
    {
      header: '',
      cell: ({ isFavorite } : EnhancedCityWeather) => isFavorite && (
        <HeartIcon
          fill="#6d3fdf"
          height={20}
          width={20}
        />
      ),
    },
  ], []);

  return (
    <Table columns={columns} items={sortedItems} loading={loading} />
  );
};

现在,我写了一些这样的测试:

Now, I wrote some tests like this:

jest.mock('../../../components/Table', () => ({
  __esModule: true,
  default: jest.fn(() => <div data-testid="Table" />),
}));

let cityWeatherCollection: EnhancedCityWeather[];
let loading: boolean;
let rerender: () => {};

beforeEach(() => {
  cityWeatherCollection = [/*...some objects...*/];

  loading = true;
  rerender = jest.fn();

  render(
    <BrowserRouter>
      <WeatherReport
        cityWeatherCollection={cityWeatherCollection}
        loading={loading}
        rerender={rerender}
      />
    </BrowserRouter>
  );
});

it('renders a Table', () => {
  expect(screen.queryByTestId('Table')).toBeInTheDocument();
});

it('passes loading prop to Table', () => {
  expect(Table).toHaveBeenCalledWith(
    expect.objectContaining({ loading }),
    expect.anything(),
  );
});

it('passes items prop to Table after sorting by isFavorite and then alphabetically', () => {
  expect(Table).toHaveBeenCalledWith(
    expect.objectContaining({
      items: cityWeatherCollection.sort((item1, item2) => (
        +item2.isFavorite - +item1.isFavorite
        || item1.name.localeCompare(item2.name)
      )),
    }),
    expect.anything(),
  );
});

如果您检查我的组件,则它具有一个名为columns的变量.我正在将该变量分配给Table组件.

If you check my component, it has a variable called columns. I am assigning that variable to Table component.

我认为,我应该测试是否将列作为道具传递给Table组件.我在想对吗?如果是这样,您能告诉我如何编写一个测试用例吗?

I think, I should test that columns are being passed as props to the Table component. Am I thinking right? If so, can you please tell me how can I write a test case for that?

此外,如果您可以建议我如何测试在column属性中声明的每个单元格,这将对您有所帮助.

Also, it will be helpful if you can suggest me how can i test each cell declared inside columns property.

推荐答案

它是不推荐,以使用React Testing Library测试实现细节,例如组件属性.相反,您应该在屏幕上声明内容.

It is not recommended to test implementation details, such as component props, with React Testing Library. Instead you should be asserting on the screen content.

expect(await screen.findByText('some city')).toBeInTheDocument();
expect(screen.queryByText('filtered out city')).not.toBeInTheDocument();


不推荐

如果您仍然想测试道具,则可以尝试以下示例代码. 来源

import Table from './Table'
jest.mock('./Table', () => jest.fn(() => null))

// ... in your test
expect(Table).toHaveBeenCalledWith(props, context)

您可能主要在以下两种情况下考虑使用这种方法.

You might consider this approach mainly on the two following scenarios.

您已经尝试了推荐的方法,但是您注意到该组件是:

  1. 使用遗留代码,因此使测试变得非常困难.重构组件也将花费很长时间或太冒险.
  2. 非常慢,并且大大增加了测试时间.该组件也已经在其他地方进行了测试.

此处

这篇关于我如何测试道具是否传递给孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆