'jest test failing 50% of the time when run with other tests

I have unit test that fails 50% of the time.

import React from 'react';
import { within } from 'client-test-utils';
import 'index';

jest.mock('components/app/cart', () => ({
   __esModule: true,
   default: () => <h1>Hello World</h1>
}));

jest.mock('api/static-data-context', () => ({
   __esModule: true,
   wrapWithStaticDataProvider: Component => Component
}));

const mockInitialize = jest.fn(() => Promise.resolve());


describe('Checkout', () => {
   let container;

   beforeEach(() => {
       container = document.createElement('div');
       document.body.appendChild(container);
       mockInitialize.mockReturnValue(Promise.resolve());
   });

   afterEach(() => {
       window.checkout.unmount();
       document.body.innerHTML = '';
       mockInitialize.mockReset();
   });  

   it('should render', async () => {
      const callback = jest.fn();
      window.checkout.render(container, { callback });

      const app = await within(container).findByText('Hello World');
      expect(app).toBeInTheDocument();
      expect(callback).toHaveBeenCalledWith('mount');
   });
});

But when I run it individually, it always passes. I also tried using queryByText but it also fails.

These sorts of failures are very hard to detect and I do not know how to fix it. Any advice?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source