javascript - 使用 Jest 对 ThreeJS 应用程序进行单元测试

标签 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();

这很正常,因为我们是 testing in a browser-like environment which has no 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 |

这是预期的行为,因为来自 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...
}));

但我很清楚这不是最佳解决方案。在此之前,我在做同样的事情,但是在 mocks/three.js ( https://jestjs.io/docs/en/manual-mocks ) 中的一个文件中,它也可以正常工作,但不能满足我的需要。

有没有办法正确测试这个文件,而不必编写大量的threejs 手动模拟?

最佳答案

我也在研究 webgl,并通过以下方式解决了这个问题。
https://github.com/AmitTeli/webgl-three-test

该方法的总结是

  • 移动所有全局变量 喜欢 现场 , 渲染器 相机到 index.html
  • 在加载页面时初始化它们。例如在这个 reactjs 示例中,它们在根组件的 componentDidMount() 中初始化。其他函数可以使用此上下文。 (您可以通过运行 yarn start 进行检查)
  • 在进行单元测试时,在 setupTest.js 中初始化它们。我们需要额外的 headless webgl 开发依赖项 - 总帐 Canvas
  • 现在有了这个设置,我们可以在 App.test.js 中运行测试(你可以通过运行 yarn test 来检查)
  • 关于javascript - 使用 Jest 对 ThreeJS 应用程序进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51330753/

    相关文章:

    javascript - 选择选项子组件不会在使用 React js 提交的表单上重置为键 0

    java - Maven Surefire 插件 + 并行构建

    javascript - import 与 typescript 1.6 和 es6 语法的内联使用

    Javascript:分割键值(带空格)

    php - 有没有办法为单个测试禁用 PHPUnit 中的代码覆盖率?

    3d - 为什么透明 Material 会导致遮挡?

    three.js - Blender 4 Web 即使在加载页面后也会不断消耗 CPU

    Three.js 使用自定义网格和 Material 进行 GPU 实例化

    javascript - 从 ng-resource head 请求访问响应头

    c# - 如何测试与数据库的连接是否成功建立?