使用Vitest测试PixiJS应用时遭遇Worker未定义错误
问题:使用Vitest测试Pixi-JS应用时出现“Worker not defined”错误
我想用Vitest对Pixi-JS应用代码做单元测试,但运行测试时报错“Worker not defined”。以下是测试代码:
/** * @vitest-environment jsdom */ import { Application } from '@pixi/node'; import { describe, it } from 'vitest'; describe('Render', function() { it('should be able to create a Render instance', async function() { new Application(); }); });
执行npm run test后的报错信息:
FAIL test/render/Render.test.ts [ test/render/Render.test.ts ] ReferenceError: Worker is not defined ❯ node_modules/@pixi/assets/lib/_virtual/checkImageBitmap.worker.mjs:20:30 ❯ test/render/Render.test.ts:1:31 1| /** 2| * @vitest-environment jsdom | ^ 3| */ 4| ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ Test Files 1 failed (1) Tests no tests Start at 20:18:55 Duration 0ms
解决方案
原因分析
你导入的是@pixi/node(针对Node.js环境的Pixi包),但测试环境指定了jsdom,而jsdom默认不提供全局的Worker对象,@pixi/node内部依赖Worker,因此触发报错。
针对Node.js端Pixi应用的测试方案
直接将测试环境切换为node,Node.js本身支持Worker对象,适配@pixi/node的运行需求:
修改后的测试代码:
/** * @vitest-environment node */ import { Application } from '@pixi/node'; import { describe, it, expect } from 'vitest'; describe('Render', function() { it('should be able to create a Render instance', async function() { const app = new Application(); expect(app).toBeDefined(); }); });
针对浏览器端Pixi应用的测试方案
如果需要测试浏览器环境下的Pixi代码,应导入@pixi/app而非@pixi/node,同时给jsdom环境手动模拟Worker对象:
/** * @vitest-environment jsdom */ // 模拟Worker全局对象 global.Worker = class Worker { constructor(url: string) { this.postMessage = () => {}; this.onmessage = null; } postMessage: (data: any) => void; onmessage: ((event: MessageEvent) => void) | null; }; import { Application } from '@pixi/app'; import { describe, it, expect } from 'vitest'; describe('Render', function() { it('should be able to create a Render instance', async function() { const app = new Application(); expect(app).toBeDefined(); }); });
根据你的实际测试场景选择对应方案即可。
内容的提问来源于stack exchange,提问作者Paul Goblin
相关产品推荐
相关产品推荐

