简体   繁体   中英

Jest test passes but .. has console message You are trying to access a property or method of the Jest environment after it has been torn down

My test passes but has a console refrenceError:

You are trying to access a property or method of the Jest environment after it has been torn down.

Test:

import {render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react';
import {create, act} from 'react-test-renderer';
import Comp1 from './Comp1';
import ReactDOM from 'react-dom';
import "@testing-library/jest-dom";
import { QueryClient, QueryClientProvider } from 'react-query';

const queryClient = new QueryClient();

it('Should wait for response', () => {
    act(() => {
        waitFor(() => {
        render(<QueryClientProvider client={queryClient}><Comp1 /></QueryClientProvider>);
        expect(screen.getByTestId('loading', {}, { timeout: 2000 })).toBeInTheDocument();
        });
    });
});

Any Idea's? this checks the response of a async/await api call.

It's an async issue, you need to add async , wait :

it('Should wait for response', async () => {
  render(
    <QueryClientProvider client={queryClient}>
      <Comp1 />
    </QueryClientProvider>
  );

  await waitFor(() => {
        expect(screen.getByTestId('loading', {})).toBeInTheDocument();
   });
});

My issue was caused by use of async methods in a helper function without using await properly.

We had extracted some business logic for navigation into a help function, but when we copied over the code we didn't turn it into an async method.

For instance, we were using waitFor without any promises or await , so the context would be accessed after the environment was torn down and this caused an issue.

Check your helpers, test setup, and other uses of async methods if you're seeing this error. Even if they're nested, it could certainly be the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM