Skip to content

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.Scene
ngtTestBed.sceneInstanceNode; // root Scene local state
ngtTestBed.canvas; // the mocked HTMLCanvasElement
ngtTestBed.destroy; // method to destroy the fixture
ngtTestBed.fireEvent; // method to fire events on an element in the scene graph
ngtTestBed.advance; // method to advance the animation loop manually per frame
ngtTestBed.toGraph; // method to convert the scene graph to a simple object

Options

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,
});
  • canvasConfiguration is an object whose role is similar to NgtCanvas inputs.

  • mockCanvasOptions is an object that allows us to customize the mocked canvas element. It accepts width and height as well as beforeReturn which is a function that allows us to return a mocked HTMLCanvasElement before the TestBed is created.

Example Scenario

For this example, we will use scene, fireEvent, and advance to test the SceneGraph component.

  • scene allows us to assert the state of the scene graph
  • fireEvent allows us to fire events on the cube
  • advance allows 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