【问题标题】:[jest]: TypeError: Object prototype may only be an Object or null: undefined[开玩笑]:TypeError:对象原型可能只是一个对象或空:未定义
【发布时间】:2021-09-04 08:17:03
【问题描述】:

在编写 jest 测试时,我需要使用 memfs 作为 Nodejs 本机文件系统模块的模拟,所以我使用了 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" 语法,因为从其他答案看来,这似乎解决了问题,但错误仍然存​​在。

任何帮助将不胜感激。

【问题讨论】:

  • “这是它的复制品。” -> How do I ask a good question? -> 在问题本身中添加一个minimal reproducible example 而不仅仅是一个链接到可能因任何原因或更改或...而无法使用的外部资源...
  • "请勿发布代码、数据、错误消息等的图片。 - 将文本复制或输入到问题中。请保留图片的使用权图表或演示渲染错误,无法通过文本准确描述的事情。”

标签: javascript typescript unit-testing jestjs


【解决方案1】:

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

似乎memfsgraceful-fs 不兼容,后者是fs-extra 的依赖项,而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

【讨论】:

    猜你喜欢
    • 2019-04-06
    • 2021-02-10
    • 2018-08-06
    • 2020-01-08
    • 2020-10-30
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多