NodeJS 为什么我的resetAllMocks不起作用

pftdvrlh  于 2022-11-04  发布在  Node.js
关注(0)|答案(3)|浏览(217)

第二个expect(fs.writeFile).toHaveBeenCalledTimes(1)(在describe('Guid for MPX')中返回一个错误,因为writeFile被调用了两次。理论上,jest.ResetAllMocks应该处理这个问题,但它没有。

'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);
  });
});

被调用的代码:

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;
  }
};
up9lanfz

up9lanfz1#

我遇到了同样的问题,直到我将jest.resetAllMocks();放在afterEach中,如下所示:

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

4xrmg8kj2#

我最终通过在每个测试开始时为writefile创建一个spy并在测试完成时清除它来使它工作:

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();
  });
});
e1xvtsh3

e1xvtsh33#

同样的事情在这里。我不得不使用spyOn以及,这可能是更好的做法。
所有人都应该小心,当不使用spyOn与复杂的库,仔细检查您的重置工作,但安全的做法是手动恢复您嘲笑的功能。
看起来有一个问题,也许是因为fs/promises是如何包含的。fs.promises是一个Getter函数,是从internal/fs/promises延迟加载的,而jest似乎无法清理jest.resetModules延迟加载的模块?

请参阅@john-james关于moduleNameMapper的相关注解:
Jest not working with fs/promises typescript
resetModules()的另一个已记录错误:
https://github.com/facebook/jest/issues/11632

相关问题