Reputation: 667
I am working on my first react unit test and would like to know if there is a best practice for grouping variables used in every unit test? I have a group of unit tests for a form that uses the same variables. I grouped them in an 'describe(){}' and would like to have the variables at the beginning of each test. My approach is below, but I am receiving an error that says 'ReferenceError: input is not defined'.
If I do not wrap them in a beforeEach(), then I receive errors for the 'screen.getByText' lines that it was 'Unable to find an element with the text' even though it's wrapped in an await.
The tests run fine if I have the variables repeated in each test, but that would be a lot of duplicated code as I have 6 tests within the describe().
import { render, fireEvent, wait, cleanup, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
describe('testing subscription form validation', () => {
beforeEach(() => {
let handleChange = jest.fn();
let {getByTestId} = render(<Form handleChange={handleChange}/>);
let input = getByTestId('test-input');
let button = screen.getByTestId('test-button');
});
it('[some test description]', async () => {
fireEvent.change(input, { target: { value: '[test value]' } });
fireEvent.click(button);
expect(screen.getByText('[button text]')).toBeInTheDocument();
await wait(() => expect(input).toHaveAttribute('value', 'test value'));
});
it('[another test]', async () => {
fireEvent.change(input, { target: { value: '' } });
fireEvent.click(button);
await wait(() => {
const requiredText = screen.getByText('This field is required');
expect(requiredText).toBeInTheDocument();
});
});
});
Thank you for taking the time to help! Any guidance would be great.
Upvotes: 1
Views: 1569
Reputation: 4643
You should dclare the variables outside the function and assign to them inside your beforeEach()
, like so:
describe('hdgsbdicg', () => {
let input;
bedoreEach(() => {
input=jest.fn(); //or whatever
}
});
Upvotes: 2