首页 > 解决方案 > 在 beforeAll/beforeEvery 中渲染相同的组件: testing-library/react

问题描述

我在单独的测试中在单个组件中测试不同的东西。我不想在每一个里面都写渲染test,但是下面的代码不起作用。

我知道清理功能会在每次测试后清除渲染的组件,这很好。

import React from "react";
import { Router } from "react-router-dom";
import { render } from "@testing-library/react";
import "@testing-library/jest-dom";

import myComp from './myComp'

const renderComponent = () => {
  return render(<myComp />);
};

describe("desc", () => {
  beforeEach(() => {
   const {getAllByText, getByText, getByRole} = renderComponent()
  });

  test("1", () => {
      console.log(getAllByText) // not defined
  });

  test("2", () => {
      console.log(getAllByText) // not defined

  });

})

上面的设置导致错误:

ReferenceError: getAllByText is not defined

我目前的解决方法是renderComponent()在 each 中包含函数调用test,但这看起来并不那么干净。

test("1", () => {
    const {getAllByText, getByText, getByRole} = renderComponent()
});

试图:

let result;
beforeEach(() => {
    result = renderComponent();
    }
test("renders success state", () => {
    const { getByText } = result;
    expect(getByText(noAccess)).toBeInTheDocument();
    expect(getByText(applyForAccessButton)).toBeInTheDocument();});

我得到的错误是:

    TypeError: Cannot read property 'getByText' of undefined

标签: reactjsjestjscomponentsreact-testing-library

解决方案


getAllByText是本地beforeEach功能,它没有在访问它的测试范围中定义。为了以这种方式可行,它应该是:

  let getAllByText, getByText, getByRole;

  beforeEach(() => {
   ({getAllByText, getByText, getByRole} = renderComponent());
  });
  ...

推荐阅读