Mar*_*rst 6 javascript unit-testing three.js jestjs
我在使用 Jest 测试 JavaScript 文件时遇到了困难,该文件封装了与 ThreeJS 的大量交互。我首先尝试不模拟 ThreeJS,但它不起作用:
? TestSuite › Should instantiate a renderer attached to a specific element of the DOM
TypeError: Cannot read property 'getExtension' of null
36 | */
37 | constructor(containerId: string) {
> 38 | this.renderer = new WebGLRenderer({ antialias: true });
39 | this.attachRenderer(containerId);
40 | this.createCamera();
41 | this.createScene();
Run Code Online (Sandbox Code Playgroud)
这是正常的,因为我们在没有 webgl context 的类似浏览器的环境中进行测试。所以我为解决这个问题所做的就是模拟three.js。
然后我嘲笑我的外部模块 jest.mock("three");
? TestSuite › Should instantiate a renderer attached to a specific element of the DOM
TypeError: this.renderer.setSize is not a function
64 | throw new Error("Cannot find DOM element object matching the specified ID: " + containerId);
65 | }
> 66 | this.renderer.setSize(window.innerWidth, window.innerHeight);
67 | element.appendChild(this.renderer.domElement);
68 | }
69 |
Run Code Online (Sandbox Code Playgroud)
这是预期的行为,因为每个来自 jest 的模拟都返回undefined,new WebGLRenderer();返回undefined而我无法对它做任何事情。
我目前的解决方法是在我的测试文件中定义我在 ThreeJS 中使用的所有内容:
jest.mock("three", () => ({
Scene: class Scene {
public add(): void {
return;
}
},
WebGLRenderer: class WebGlRenderer {
public render(): void {
return;
}
public setSize(): void {
return;
}
}
// And a lot more...
}));
Run Code Online (Sandbox Code Playgroud)
但我很清楚这不是最佳解决方案。在此之前,我正在做同样的事情,但在 mocks/three.js ( https://jestjs.io/docs/en/manual-mocks )中的一个文件中,它也工作正常,但不能满足我的需要。
有没有办法正确测试这个文件,而不必编写大量的 Threejs 手动模拟?
我也在研究 webgl 这个并通过以下方式解决了这个问题。 https://github.com/AmitTeli/webgl-two-test
该方法的总结是
yarn start)yarn test)| 归档时间: |
|
| 查看次数: |
2203 次 |
| 最近记录: |