模拟 fs readFile 会导致无法监视原始值;未定义给定

5 unit-testing node.js typescript jestjs

方法很简单:

import fs from 'fs';
function getFile(path) {
  return new Promise(function(resolve, reject) {
    fs.readFile(path, 'utf8', function(err, success) {
      if (err) reject(err);
      else resolve(success);
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

它是从其他方法调用的,但我需要模拟 readFile 并且我尝试了 3 个选项,全部给出错误:

尝试一:

  it('should get data', async () => {

    const spy = jest.spyOn(fs,'readFile')
    .........
    });
Run Code Online (Sandbox Code Playgroud)

它停在出现错误的行:

无法监视原始值;未定义给定

尝试二:

  let readFileCallback;

  jest.spyOn(fs, 'readFile').mockImplementation((path, options, callback) => {
    readFileCallback = callback;
  });
Run Code Online (Sandbox Code Playgroud)

由于选项参数而引发实现错误。

类型为“(path:any, options:any,callback:any) => void”的参数不可分配给类型为“(path:string | number | Buffer | URL,callback:(err: ErrnoException, data: Buffer)”的参数) => 无效) => 无效'。

如果我删除选项参数,我会收到相同的错误:

无法监视原始值;未定义给定

我如何模拟 readFile 以便它返回一些文本?

sli*_*wp2 0

jest.spyOn(object, methodName)应该可以工作。你的第二次尝试即将完成。您面临 TypeScript 的类型问题。要解决此类型问题,您可以使用类型断言来处理此问题。

\n

例如

\n

index.ts:

\n
import fs from \'fs\';\n\nfunction getFile(path): Promise<string> {\n  return new Promise(function(resolve, reject) {\n    fs.readFile(path, \'utf8\', function(err, success) {\n      if (err) {\n        reject(err);\n      } else {\n        resolve(success);\n      }\n    });\n  });\n}\n\nexport { getFile };\n
Run Code Online (Sandbox Code Playgroud)\n

index.test.ts:

\n
import fs, { PathLike } from \'fs\';\nimport { getFile } from \'./\';\n\ndescribe(\'63748243\', () => {\n  it(\'should read file\', async () => {\n    const readFileSpy = jest.spyOn(fs, \'readFile\').mockImplementation(((\n      path: PathLike | number,\n      options: { encoding?: null; flag?: string } | undefined | null,\n      callback: (err: NodeJS.ErrnoException | null, data: string) => void,\n    ) => {\n      if (typeof options === \'string\' && options === \'utf8\') {\n        callback(null, \'123\');\n      }\n    }) as typeof fs.readFile);\n    const actual = await getFile(\'/fake/path\');\n    expect(actual).toEqual(\'123\');\n    expect(readFileSpy).toBeCalledWith(\'/fake/path\', \'utf8\', expect.any(Function));\n    readFileSpy.mockRestore();\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

带有覆盖率报告的单元测试结果:

\n
 PASS  src/stackoverflow/63748243/index.test.ts (8.99s)\n  63748243\n    \xe2\x9c\x93 should read file (6ms)\n\n----------|----------|----------|----------|----------|-------------------|\nFile      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |\n----------|----------|----------|----------|----------|-------------------|\nAll files |    85.71 |       50 |      100 |    85.71 |                   |\n index.ts |    85.71 |       50 |      100 |    85.71 |                 7 |\n----------|----------|----------|----------|----------|-------------------|\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        10.04s\n
Run Code Online (Sandbox Code Playgroud)\n

源代码: https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/63748243

\n