我在单独的测试中用一个组件测试不同的东西。我希望不必在每个单独的test中都编写render,但是下面的代码无法工作。
据我所知,清理功能会在每次测试后清除呈现的组件,所以这很好。
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我目前的解决方法是在每个test中包含renderComponent()函数调用,但这看起来并不是很干净。
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发布于 2020-11-20 18:56:40
getAllByText是beforeEach函数的本地函数,它没有在访问它的测试范围中定义。为了使这种方法可行,它应该是:
let getAllByText, getByText, getByRole;
beforeEach(() => {
({getAllByText, getByText, getByRole} = renderComponent());
});
...https://stackoverflow.com/questions/64927641
复制相似问题