I'm testing different things in a single component in separate tests. I want to not have to write render inside every single test, but the code underneath does not work.
I have understood that the cleanup function clears the rendered component after each test, so that is good.
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
});
})
The setup above results in the error:
ReferenceError: getAllByText is not defined
My current workaround is to include renderComponent() function call in each test, but this does not look so clean.
test("1", () => {
const {getAllByText, getByText, getByRole} = renderComponent()
});
Attempt:
let result;
beforeEach(() => {
result = renderComponent();
}
test("renders success state", () => {
const { getByText } = result;
expect(getByText(noAccess)).toBeInTheDocument();
expect(getByText(applyForAccessButton)).toBeInTheDocument();});
Error I get then is:
TypeError: Cannot read property 'getByText' of undefined