简体   繁体   English

如何循环遍历子数组并检查组件是否存在 React 测试库

[英]How do I loop through child array and check if component exists React Testing Library

Currently I want to loop through all the child components and check if all the components exist with React Testing Library.目前我想遍历所有子组件并检查是否所有组件都存在于 React 测试库中。 The test below gave me the following error:下面的测试给了我以下错误:

TypeError: component.contains is not a function类型错误:component.contains 不是 function

Not sure what is wrong with this test, but it seems it cannot test based on the test ID.不确定此测试有什么问题,但似乎无法根据测试 ID 进行测试。

 import React from 'react' import { RandomMeals } from '../RandomMeals/RandomMeals'; import ListMeals from '../ListMeals/ListMeals'; import { SearchBar } from '../SearchBar/SearchBar'; import { TopBar } from '../TopBar/TopBar'; import SearchResult from '../SearchResult/SearchResult'; export const AppComponent = () => ( <div className="app-container" data-testid="app-component-test"> <TopBar/> <div className="column app-mobile app-desktop-left"> <RandomMeals/> <SearchBar/> <SearchResult/> </div> <div className="column app-mobile app-desktop-right"> <ListMeals/> </div> </div> ) test("It should check if components exist", () => { render( <Provider store={store}> <AppComponent/> </Provider> ); const component = screen.getAllByTestId("app-component-test"); console.log(component); expect(component.contains(<RandomMeals/>)).toBe(true); });

在此处输入图像描述

If you want to check that <RandomMeals /> is being rendered, you should query based on that element:如果要检查<RandomMeals />是否正在呈现,则应基于该元素进行查询:

function RandomMeals(props) {
  return <div data-testid="random-meals-test">...</div>
}

test("It should check if components exist", () => {
  const screen = render(
    <Provider store={store}>
      <AppComponent/>
    </Provider>
  );

  expect(screen.getByTestId("random-meals-test")).not.toThrow()
  // alternatively
  expect(screen.queryByTestId("random-meals-test")).toBeTruthy()
});

To answer your question about what's wrong with the test, getAllByTestId returns an array of DOM nodes that match the query.为了回答您关于测试出了什么问题的问题, getAllByTestId返回与查询匹配的 DOM 节点数组。 And Array#contains is not a method in JavaScript.并且Array#contains不是 JavaScript 中的方法。 You could use getByTestId to return a single DOM node, which does have a contains method, but even in that case you cannot pass arbitrary JSX as an argument.您可以使用getByTestId返回单个 DOM 节点,该节点确实具有 contains 方法,但即使在这种情况下,您也不能将任意 JSX 作为参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM