javascript - [ Jest ] : TypeError: Object prototype may only be an Object or null: undefined

标签 javascript typescript unit-testing jestjs

在编写 Jest 测试时,我需要使用 memfs作为 Nodejs native 文件系统模块的模拟,所以我使用了 jest 的 manual mocks ,但我收到此错误:

> rimraf tests/{coverage,public} && jest

 PASS  tests/x.test.ts (19.926 s)
 FAIL  tests/mix.test.ts
  ● Test suite failed to run

    TypeError: Object prototype may only be an Object or null: undefined
        at Function.setPrototypeOf (<anonymous>)

      at node_modules/graceful-fs/polyfills.js:139:39
      at patch (node_modules/graceful-fs/polyfills.js:141:5)
      at patch (node_modules/graceful-fs/graceful-fs.js:104:3)
      at Object.<anonymous> (node_modules/graceful-fs/graceful-fs.js:96:18)
      at Object.<anonymous> (node_modules/fs-extra/lib/fs/index.js:5:12)

 PASS  tests/options.test.ts (35.412 s)

Test Suites: 1 failed, 2 passed, 3 total
Tests:       6 passed, 6 total
Snapshots:   0 total
Time:        36.834 s
Ran all test suites.

以下是用于最小重现错误的文件:

// src/index.ts
// this is just a minimal reproduction
import "laravel-mix";
import fs from "fs";

export default function getContent(path: string) {
    return fs.readFileSync(path, "utf-8");
}
// tests/index.test.ts

import path from "path";
import fs from "fs";
import memfs from "memfs";
import getContent from "../src";

// Use memfs instead of native fs module.
jest.mock("fs");
jest.mock("fs/promises");

beforeAll(() => {
  memfs.fs.mkdirSync(path.resolve(), {recursive: true});
});

// this is for demonstration only.
test("should mock fs", () => {
    expect(fs).toBe(memfs.fs);
});

test("returns content from memfs", () => {
    memfs.fs.writeFileSync("test.txt", "test text");

    const result = getContent("test.txt");

    expect(result).toBe("test text");
});

// more tests
// jest.config.js

module.exports = {
    collectCoverageFrom: ["src/*.ts"],
    coverageDirectory: "tests/coverage",
    preset: "ts-jest",
    testEnvironment: "node",
    testMatch: ["<rootDir>/tests/**/*.test.ts"],
};
// tsconfig.json

{
  "compilerOptions": {
    "downlevelIteration": true,
    "declaration": true,
    "declarationDir": "dist",
    "strict": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "noImplicitReturns": true,
    "noImplicitOverride": true,
    "importHelpers": true
  }
}
// package.json

{
  "name": "jest-mock-error-reproduction",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.ts",
  "scripts": {
    "test": "jest"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/jest": "^27.0.1",
    "@types/node": "^16.7.8",
    "@types/serve-static": "^1.13.10",
    "jest": "^27.1.0",
    "laravel-mix": "^6.0.29",
    "memfs": "^3.2.4",
    "ts-jest": "^27.0.5",
    "typescript": "~4.2.0"
  }
}

和手动模拟文件:

// __mocks__/fs.ts

import {fs} from "memfs";

export default fs;
// __mocks__/fs/promises.ts

import {fs} from "memfs";

export default fs.promises;

请注意,当我删除时:

jest.mock("fs");
jest.mock("fs/promises");

来自 tests/index.test.ts,测试按预期失败。

我尝试调试产生错误的源代码,但找不到问题。

我还尝试在 __mock__ 文件中使用 import * as memfs from "memfs" 语法,因为从其他答案看来这似乎解决了问题,但是错误仍然存​​在。

如有任何帮助,我们将不胜感激。

最佳答案

我能够将问题的根源缩小到依赖项。

好像memfsgraceful-fs 不兼容这是 fs-extra 的依赖项这反过来又是我在自己的代码中使用的库的依赖项 ( laravel-mix )。所以这里是错误的最小再现:

// tests/index.test.ts

import fs from "fs";
import memfs from "memfs";
import "graceful-fs"; // comment this and the test should pass.

jest.mock("fs");
jest.mock("fs/promises");

test("should mock fs", () => {
    expect(fs).toBe(memfs.fs);
});

为了解决我的问题,我更改了正在使用的虚拟文件系统库。我从 memfs 切换过来的至 mock-fs .

首先,我安装了mock-fs@types/mock-fs:

npm i -D mock-fs @types/mock-fs

然后我在 tests/index.test.ts 中使用它:

// tests/index.test.ts

import path from "path";
import fs from "fs";
import mock_fs from "mock-fs";
import getContent from "../src";

beforeEach(() => {
    mock_fs();
});

afterEach(() => {
    mock_fs.restore();
});

test("returns content from mocked fs", () => {
    fs.writeFileSync("test.txt", "test text");

    const result = getContent("test.txt");

    expect(result).toBe("test text");
});

// more tests

关于javascript - [ Jest ] : TypeError: Object prototype may only be an Object or null: undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69048470/

相关文章:

java - Java 单元测试能否像 .NET 那样隐藏生产代码的接缝接口(interface)?

ruby-on-rails - 在 Controller 中使用 using 方法测试辅助方法

javascript - 跑道 Javascript Web 表单

javascript - 使用 Angular 显示 json 响应中的特定值

node.js - 两个日期之间的天数 - typescript

node.js - NG Live Development Server 与传统 Web 服务器

ruby-on-rails - Rails 组织单元测试的方式是什么?

javascript - react js : Accessing state of other components

javascript - 图片不存在时不显示下一个/图片组件

angular - 如何在 ionic 2 和 Angular 2 上使用 http post 方法?