如何使用 jest 模拟带有 promise 的 fs.writeFile 调用?

How do I mock an fs.writeFile call with a promise using jest?

在尝试了很多方法之后,我遇到了困难。使用我现在的代码,一旦 fs.writeFile 被伪造,软件就会抛出以下错误:

Error: ENOENT: no such file or directory (followed by the path and file).

使用 fs 写入文件的简单例程:

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

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

单元测试:

'use strict';
const fs = require('memfs');
const path = require('path');
jest.mock('fs');

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

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

describe('Write file', () => {
  it('should write a file', async () => {
    try {
      await fs.writeFile(`${directoryPath}/test-file`, 'test data');
      const result = await writeData('test data', 'test-file');
      expect(result).toEqual('test-file written')
    } catch (err) {
      console.log('error=', err);
    }
  });
});

你没有正确模拟 fs.promises

index.js:

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

const writeData = async (data, file) => {
  const directoryPath = path.join(__dirname, '../wiremock/stubs/mappings');
  try {
    await fs.writeFile(`${directoryPath}/${file}`, data);
    return `${file} written`;
  } catch (err) {
    return err;
  }
};

module.exports = { writeData };

index.test.js:

const { writeData } = require('.');

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

describe('Write file', () => {
  it('should write a file', async () => {
    const result = await writeData('test data', 'test-file');
    expect(result).toEqual('test-file written');
  });
});

测试结果:

 PASS  Whosebug/72115160/index.test.js
  Write file
    ✓ should write a file (3 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.857 s, estimated 12 s