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:

1
const ngtTestBed = NgtTestBed.create(SceneGraph);
2
ngtTestBed.fixture; // ComponentFixture<NgtTestCanvas>
3
ngtTestBed.store; // NgtSignalStore<NgtState>
4
ngtTestBed.scene; // root THREE.Scene
5
ngtTestBed.sceneInstanceNode; // root Scene local state
6
ngtTestBed.canvas; // the mocked HTMLCanvasElement
7
ngtTestBed.destroy; // method to destroy the fixture
8
ngtTestBed.fireEvent; // method to fire events on an element in the scene graph
9
ngtTestBed.advance; // method to advance the animation loop manually per frame
10
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.

1
const ngtTestBed = NgtTestBed.create(SceneGraph, {
2
mockCanvasOptions: { width: 1280, height: 720 },
3
canvasConfiguration: {
4
camera: { position: [0, 0, 5] },
5
shadows: true
6
},
7
...TestBedOptions,
8
});
  • 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
1
import { NgtTestBed } from 'angular-three/testing';
2
3
describe('SceneGraph', () => {
4
it('should render', async () => {
5
const { scene, fireEvent, advance } = NgtTestBed.create(SceneGraph);
6
});
7
});

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

1
import { NgtTestBed } from 'angular-three/testing';
2
3
describe('SceneGraph', () => {
4
it('should render', async () => {
5
const { scene, fireEvent, advance } = NgtTestBed.create(SceneGraph);
6
expect(scene.children.length).toEqual(1);
7
const mesh = scene.children[0] as Mesh;
8
expect(mesh.isMesh).toEqual(true);
9
});
10
});

Next, we will test the Mesh events with fireEvent