How to ensure jest mocks always reset?

195 Views Asked by At

I have a couple of tests that are acting flaky. Sometimes they pass, sometimes not. How do I mock out a module but ensure that the call count gets reset between tests? What am I doing wrong?

jest.mock('dockerode')  

import Docker from 'dockerode';

import {serviceExists, getDocker} from './methods'

import { mockContainerList } from './mockData'

describe('docker methods', function() {

    beforeEach(() => {
        jest.restoreAllMocks();
      })

    it('should validate that the servicename is currently running on the host', async function() {
        await Docker.mock.instances[0].listContainers.mockResolvedValueOnce(mockContainerList)
        let serviceName = 'buildtest';
        let funcCall = await serviceExists(serviceName); //?
        expect(Docker.mock.instances[0].listContainers.mock.calls.length).toEqual(1);

        expect(funcCall).toBeTruthy()
    });

    it('should return false if the servicename is NOT currently running on the host', async function() {

        await Docker.mock.instances[0].listContainers.mockResolvedValueOnce(mockContainerList);
        let serviceName = 'helloWorld';  
        let funcCall = await serviceExists(serviceName); //?  
        Docker.mock.instances[0].listContainers.mock.calls;  //? 
        expect(Docker.mock.instances[0].listContainers.mock.calls.length).toEqual(1);    // <-- this fails (but only sometimes)

        expect(funcCall).toBeFalsy();
    });

});
0

There are 0 best solutions below