'Why is my resetAllMocks not working in jest

The second expect(fs.writeFile).toHaveBeenCalledTimes(1) (in describe('Guid for MPX') returns an error because the writeFile has been called twice. In theory, jest.ResetAllMocks should take care of this but it doesn’t.

'use strict';
const fs = require('fs').promises;
const path = require('path');

const guidForMpxInvalid = require('../json/guid-for-Mpx-invalid.json')
const data = require('../../../data/sandbox-data-model.json');

jest.mock('fs', () => ({
  promises: {
    writeFile: jest.fn(),
  },
}));

const {
  writeData,
  createGuidForMpx,
  createMpxForGuid,
} = require('../app/transform');

const directoryPath = path.join(__dirname, '../../../wiremock/stubs/mappings');

describe('Write file', () => {
  beforeEach(() => {
    jest.resetAllMocks();
  });

  it('should write a file', async () => {
    const result = await writeData(guidForMpxInvalid, 'guid-for-Mpx-invalid-Mpx.json');
    expect(result).toEqual('guid-for-Mpx-invalid-Mpx.json written');
    expect(fs.writeFile).toHaveBeenCalledTimes(1);
  });
});

describe('Guid for MPX', () => {
  it('should create JSON file for the GUID of a particular MPX', async ()=>{
    const result = await createGuidForMpx(data.Customers[0].guid, data.Customers[0].Customer_Overlays.core.Personal_Details.MPX);
    expect(result).toEqual('guid-for-Mpx-AB123456B.json written');
    expect(fs.writeFile).toHaveBeenCalledTimes(1);
  });
});

The code being called:

const writeData = async (data, file) => {
  const directoryPath = path.join(__dirname, '../../wiremock/stubs/mappings');

  try {
    fs.writeFile(`${directoryPath}/${file}`, data);
    return `${file} written`
  } catch (err) {
    return err;
  }
};


Solution 1:[1]

I was experiencing the same problem until I placed jest.resetAllMocks(); inside afterEach like so:

afterEach(() => {
  jest.resetAllMocks();
});

Solution 2:[2]

I eventually got this working by creating a spy for the writefile at the start of each test and clearing it when the test is done:

it('should write a file', async () => {
    const writeFileSpy = jest.spyOn(fs, 'writeFile');
    const result = await writeData(guidForMPXInvalid, 'guid-for-mpx-invalid-mpx.json');
    expect(result).toEqual('guid-for-mpx-invalid-mpx.json written');
    expect(writeFileSpy).toHaveBeenCalledTimes(1);
    writeFileSpy.mockClear();
  });
});

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Ovidijus Parsiunas
Solution 2 jenkinz