mock fs.readFile with typescript

bqf10yzr  于 2023-06-30  发布在  TypeScript
关注(0)|答案(1)|浏览(160)

我尝试模拟fs.readFile:

fs.readFile = jest.fn((_, callback) => callback(null, JSON.stringify('sample')));

我试着测试这个函数:

export const readFileAsynchronously = async (pathToFile: string) => {
  const fullPath = join(__dirname, pathToFile);
  if (existsSync(fullPath)) {
    const fileContent = await readFile(fullPath);
    return fileContent.toString();
  }

  return null;
};

而且我想在不阅读真实的文件的情况下测试这个函数,可以吗?测试是:

test('should return file content if file exists', async () => {
    jest.mock('fs');
    const existsSync = () => true;
    fs.existsSync = existsSync;
    fs.readFile = jest.fn((_, callback) => {
      return callback(null, JSON.stringify('sample'));
    });
    jest.mock('path');
    path.join = (path: string) => path;
    const pathToFile = './test.txt';
    const result = await readFileAsynchronously(pathToFile);
    expect(result).toEqual('sample');
  });

但是我得到了一个类型错误属性__promisify__不存在于类型“Mock<any,[_:任何,回调:any]、any>”,并且在类型“typeof readFile”中是必需的。我又试了一个变种:

const mockedFs = fs as jest.Mocked<typeof fs>;
    const existsSync = () => true;
    fs.existsSync = existsSync;
    mockedFs.readFile.mockImplementationOnce(
      () =>
        new Promise(function (resolve) {
          return resolve('test');
        }),
    );

但我有一个错误:

TypeError: mockedFs.readFile.mockImplementationOnce is not a function

我不知道该怎么解决。拜托你能帮帮我吗

bvjxkvbb

bvjxkvbb1#

首先,readFile不是一个承诺。你需要使用一个回调函数或者使用一个不同的函数readFileSync
您的函数没有正确实现,这里是修复的版本

import { join } from 'path';
import { existsSync, readFile } from 'fs';
export const readFileAsynchronously = async (pathToFile: string) => {
  const fullPath = join(__dirname, pathToFile);
  if (existsSync(fullPath)) {
    // Making it to resolve when callback is invoked
    return new Promise((resolve, reject) => {
      readFile(fullPath, 'utf8', (error, fileContent) => {
        if (error) return reject(error);
        resolve(fileContent);
      });
    });
  }

  return Promise.reject(new Error('File not found'));
};

下面是您的测试实现

jest.mock('fs', () => ({
  existsSync: jest.fn().mockResolvedValue(true),
  readFile: jest.fn().mockImplementation((path, options, callback) => {
    callback(null, 'my file content');
  }),
}));

test('should resolve without reading the actual file', async () => {
  const result = await readFileAsynchronously('test.txt');
  expect(result).toBe('my file content');
});

相关问题