You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vitest测试cube.js报错:因index.js的Three.js依赖导入问题

解决Vitest测试cube.js函数时的Three.js依赖导入问题

方案1:重构代码分离无依赖函数(推荐)

既然generateRandomMoves本身不依赖index.js和Three.js,最彻底的解决方式是把这类纯逻辑函数从依赖图形库的模块中抽离:

  • 创建独立工具文件(比如cube-utils.js),将generateRandomMoves迁移进去:
// cube-utils.js
export function generateRandomMoves(difficulty) {
  // 原函数逻辑代码
}
  • 修改cube.js,从工具文件导入该函数,仅保留必要的依赖(移除对index.js的不必要导入)
  • 测试文件直接导入工具文件:
// cube.test.js
import { generateRandomMoves } from "./cube-utils.js";

it("should return an array of random moves with a length of 'difficulty'", () => {
  const difficulty = 2;
  const randomMoves = generateRandomMoves(difficulty);
  expect(randomMoves.length).toBe(difficulty);
});

方案2:在Vitest中Mock不必要的依赖

如果暂时不想重构代码,可通过Vitest的mock功能跳过无关依赖的加载:

Mock整个index.js

在测试文件顶部添加mock,因为generateRandomMoves不使用index.js的导出,返回空对象即可:

// cube.test.js
import { vi } from 'vitest';
// Mock index.js,避免加载其依赖的Three.js模块
vi.mock('./index.js', () => ({}));

import { generateRandomMoves } from "./cube.js";

it("should return an array of random moves with a length of 'difficulty'", () => {
  const difficulty = 2;
  const randomMoves = generateRandomMoves(difficulty);
  expect(randomMoves.length).toBe(difficulty);
});

单独Mock OrbitControls

如果报错直接来自OrbitControls的导入,可针对性mock该模块:

// cube.test.js
import { vi } from 'vitest';
vi.mock('three/examples/jsm/controls/OrbitControls', () => ({}));

import { generateRandomMoves } from "./cube.js";

it("should return an array of random moves with a length of 'difficulty'", () => {
  const difficulty = 2;
  const randomMoves = generateRandomMoves(difficulty);
  expect(randomMoves.length).toBe(difficulty);
});

内容的提问来源于stack exchange,提问作者user11909157

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 21:45:36