reactjs - 在 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
解决方案
getAllByText
是本地beforeEach
功能,它没有在访问它的测试范围中定义。为了以这种方式可行,它应该是:
let getAllByText, getByText, getByRole;
beforeEach(() => {
({getAllByText, getByText, getByRole} = renderComponent());
});
...
推荐阅读
- gis - 如何在给定纬度和经度arcGIS的情况下获取感兴趣区域的图像?
- c++ - 是`foo
` 当 foo 是一个接受单个模板参数的结构时合法吗? - r - R中商的奇怪行为
- php - 如何在 laravel 中使用 REST API 访问谷歌业务 API
- python - 为什么“a = a + a”不是循环结构,而“a.append(a)”是循环结构?
- javascript - 显示带有点击功能的图像
- ios - React Native ios build - 修改 node_modules 包中的文件
- django - 对 CBV 使用 Django“规则”不起作用
- php - 处理时表单标签位置会影响用户输入吗?
- swift - 在 Swift 中实例化一个新的 Codable 对象的最简单方法是什么?