NgtTestBed
NgtTestBed is a utility from angular-three/testing that abstracts TestBed to make it easier to test our scene graph components.
create()
NgtTestBed exposes a single static method create that accepts a Component class and returns an object with the following properties:
const ngtTestBed = NgtTestBed.create(SceneGraph);ngtTestBed.fixture; // ComponentFixture<NgtTestCanvas>ngtTestBed.store; // NgtSignalStore<NgtState>ngtTestBed.scene; // root THREE.ScenengtTestBed.sceneInstanceNode; // root Scene local statengtTestBed.canvas; // the mocked HTMLCanvasElementngtTestBed.destroy; // method to destroy the fixturengtTestBed.fireEvent; // method to fire events on an element in the scene graphngtTestBed.advance; // method to advance the animation loop manually per framengtTestBed.toGraph; // method to convert the scene graph to a simple objectOptions
create accepts an optional second argument that allows us to pass in options to customize the TestBed.
const ngtTestBed = NgtTestBed.create(SceneGraph, { mockCanvasOptions: { width: 1280, height: 720 }, canvasConfiguration: { camera: { position: [0, 0, 5] }, shadows: true, }, ...TestBedOptions,});-
canvasConfigurationis an object whose role is similar toNgtCanvasinputs. -
mockCanvasOptionsis an object that allows us to customize the mocked canvas element. It acceptswidthandheightas well asbeforeReturnwhich is a function that allows us to return a mockedHTMLCanvasElementbefore theTestBedis created.
Example Scenario
For this example, we will use scene, fireEvent, and advance to test the SceneGraph component.
sceneallows us to assert the state of the scene graphfireEventallows us to fire events on the cubeadvanceallows us to advance the animation loop manually per frame
import { NgtTestBed } from 'angular-three/testing';
describe('SceneGraph', () => { it('should render', async () => { const { scene, fireEvent, advance } = NgtTestBed.create(SceneGraph); });});With scene, we can assert the state of the scene graph. We can assert
however we want to. To keep things simple, we will just assert that the root Scene has a child which is a Mesh
import { NgtTestBed } from 'angular-three/testing';
describe('SceneGraph', () => { it('should render', async () => { const { scene, fireEvent, advance } = NgtTestBed.create(SceneGraph); expect(scene.children.length).toEqual(1); const mesh = scene.children[0] as Mesh; expect(mesh.isMesh).toEqual(true); });});Next, we will test the Mesh events with fireEvent