Jest.js TypeError:无法读取未定义的属性(阅读“html”)

vs91vp4v  于 2023-02-01  发布在  Jest
关注(0)|答案(3)|浏览(318)

我正试着把Jest介绍给我目前的项目。
但是,在初始安装过程中,我遇到了这个错误,它运行不正常。
我该如何解决这个问题?
我目前正在使用vue-cli中的vue2。

● Test suite failed to run

    TypeError: Cannot read properties of undefined (reading 'html')

      at new JSDOMEnvironment (node_modules/jest-environment-jsdom/build/index.js:72:44)
      at async TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:317:13)
      at async runJest (node_modules/@jest/core/build/runJest.js:407:19)
      at async _run10000 (node_modules/@jest/core/build/cli/index.js:338:7)
      at async runCLI (node_modules/@jest/core/build/cli/index.js:190:3)

这是我的测试代码。

import SettlementProcessing from "@/views/calculate/SettlementProcessing.vue";
import { shallowMount } from "@vue/test-utils";
import Vuetify from "vuetify";
describe("Settlement Component", () => {
  let vuetify;
  beforeEach(() => {
    vuetify = new Vuetify();
  });
  it("정산 처리 타이틀이 나와야 한다.", () => {
    const sc = shallowMount(SettlementProcessing, { vuetify });
    expect(true).toBe(true);
  });
});

这是我的包. json。

"devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/test-utils": "^2.0.0-rc.21",
    "babel-core": "^7.0.0-bridge.0",
    "babel-jest": "^28.1.0",
    "jest": "^28.1.0",
    "vue-cli-plugin-vuetify": "~2.4.0",
    "vue-jest": "^3.0.7",
  }

这是我的jest.config.json。

// jest.config.js
module.exports = {
  preset: "@vue/cli-plugin-unit-jest",
  moduleFileExtensions: [
    "js",
    "json",
    "vue",
  ],
  transform: {
    "^[^.]+.vue$": "vue-jest",
    "^.+\\.js$": "babel-jest",
  },
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
  },
  testMatch: [
    "**/__tests__/**/*.[jt]s?(x)",
    "**/?(*.)+(spec|test).[jt]s?(x)",
  ],
  testPathIgnorePatterns: ["/node_modules/", "/dist/"],
  collectCoverage: false,
  collectCoverageFrom: ["**/*.{js,vue}", "!**/node_modules/**"],
};

我该如何解决这个问题?

j2qf4p5b

j2qf4p5b1#

我在把react应用更新到jest 28时遇到了同样的问题,这个问题是jest-environment-jsdom包丢失了,而在jest 27中还没有这个包。
参见https://jestjs.io/docs/28.x/upgrading-to-jest28

mf98qq94

mf98qq942#

您应该创建一个localVue示例并在其上使用Vuetify。这可以在tests/setup.js文件(为所有jest测试运行)中实现,也可以在使用Vuetify的每个单元测试中单独实现。
不带setup.js的示例代码(如果使用setup.js,代码会略有不同,可以查看下面的文档)

import SettlementProcessing from "@/views/calculate/SettlementProcessing.vue";
import { createLocalVue, shallowMount } from "@vue/test-utils";
import Vuetify from "vuetify";

const localVue = createLocalVue()
localVue.use(Vuetify)

describe("Settlement Component", () => {
  it("정산 처리 타이틀이 나와야 한다.", () => {
    const sc = shallowMount(SettlementProcessing, { localVue } );
    expect(true).toBe(true);
  });
});

文档在这里:https://vuetifyjs.com/en/getting-started/unit-testing/#bootstrapping-vuetify

30byixjq

30byixjq3#

通过添加jest-environment-jsdom为我修复了它。

相关问题