开玩笑的自动模拟失败:TypeError:fs.​​readdirSync不是一个函数

时间:2020-08-17 21:55:27

标签: javascript node.js jestjs

我正在尝试生成“ fs”模块的自动模型,然后对其进行扩展,但是我的实现无法正常工作:

// /home/user/cp/projectName/__mocks__/fs.js

const fs = jest.createMockFromModule('fs');

function readdirSync(fileName) {
  console.log(`The file name passed to this fake fs.readdirSync method is: ${fileName}`);

  return 'return value from fake fs.readdirSync';
}

function specialMethod() {
  return 'returned from the special method';
}

fs.readdirSync = readdirSync;
fs.specialMethod = specialMethod;

exports = fs;

上面的__mocks__文件夹是node_modules文件夹的同级文件。

运行测试文件似乎忽略了上面的模拟模块:

// /home/user/cp/projectName/src/captureCallData/__tests__/unit.test.ts

/* eslint-disable no-undef */
jest.mock('fs');
const fs = require('fs');

test('test fs.specialMethod', () => {
  const result = fs.specialMethod();
});

function useFsInternally(fakeFileName: string) {
  return fs.readdirSync(fakeFileName);
}

test('test mocking functionality', () => {
  const result: string = useFsInternally('testInput');

  expect(result).toStrictEqual('wrong value');
});

test fs.specialMethod

    TypeError: fs.specialMethod is not a function

      10 | 
      11 | test('test fs.specialMethod', () => {
    > 12 |   const result = fs.specialMethod();
         |                     ^
      13 | });
      14 | 
      15 | function useFsInternally(fakeFileName: string) {

      at Object.<anonymous> (src/captureCallData/__tests__/unit.test.ts:12:21)

  ● test mocking functionality

    TypeError: fs.readdirSync is not a function

      14 | 
      15 | function useFsInternally(fakeFileName: string) {
    > 16 |   return fs.readdirSync(fakeFileName);
         |             ^
      17 | }
      18 | 
      19 | test('test mocking functionality', () => {

      at useFsInternally (src/captureCallData/__tests__/unit.test.ts:16:13)
      at Object.<anonymous> (src/captureCallData/__tests__/unit.test.ts:20:26)                             

此配置不正确吗?错过了哪一步?

以下是相关库:

"dependencies": {
    "typescript": "^3.9.7"
  },
  "devDependencies": {
    "@types/jest": "^26.0.9",
    "jest": "^26.2.2",
    "ts-jest": "^26.1.4"
  }

也尝试过

  • importexport语法而不是require()。在这种情况下,实际的fs模块似乎是导入的,而不是模拟的:
    src/captureCallData/__tests__/unit.test.ts:12:21 - error TS2339: Property 'specialMethod' does not exist on type 'typeof import("fs")'.

    12   const result = fs.specialMethod();
                           ~~~~~~~~~~~~~
    src/captureCallData/__tests__/unit.test.ts:20:9 - error TS2322: Type 'string[]' is not assignable to type 'string'.

    20   const result: string = useFsInternally('testInput');
               ~~~~~~

1 个答案:

答案 0 :(得分:1)

exports是局部变量,最初等于module.exports,并包含对导出对象的引用。它应该被突变,而不是重新分配。 exports = fs仅替换局部变量的值,不影响导出的值。

应该是

module.exports = fs;

Object.assign(exports, fs);