reactjsjestjs

How avoid the multiple render with JEST?


I have two 'test', and in both, I'm using the same component.

How to avoid this? Exist one way of reutilized for this?

describe('AppbarGlobal [GLOBAL COMPONENT]', () => {
    test('Should be have the [TEXTS]', async () => {
        render(<AppbarGlobal />);
        expect(screen.getByText(/dApp - Superior Electoral Court/i)).toBeInTheDocument();
    });

    test('Should be have the [COMPONENTS]', async () => {
        render(<AppbarGlobal />);

        const logotype = screen.getByRole('img');
        const button = screen.getByText(/Connect Wallet/i);

        expect(logotype).toBeInTheDocument();
        expect(button).toBeInTheDocument();
    });

    test('Should be working the Connect Wallet [BUTTON]', async () => {
        render(<AppbarGlobal />);
        expect(fireEvent.click(screen.getByText(/Connect Wallet/i))).toBeTruthy();
    });
});

Solution

  • You can avoid writing out every render() call by using beforeEach:

    beforeEach(() => {
      render(<AppbarGlobal />);
    });
    

    You shouldn't, however, use the same rendered instance across different tests.