How to run Jest tests with Phaser


This post explains how to run Jest tests with Phaser.

Prerequisites

Given you have jest and phaser installed:

npm install --save-dev jest phaser

And a single test:

// index.test.js
const Phaser = require('Phaser');

it('passes', () => {
  expect(Phaser).toBeTruthy();
});

Environment

Run your test:

npx jest

You’ll get an error:

ReferenceError: HTMLVideoElement is not defined

This is because Jest’s testEnvironment defaults to node, so update your Jest config to use jsdom:

// jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
};

Run your test:

npx jest

You’ll get an error:

● Validation Error:

  Test environment jest-environment-jsdom cannot be found. Make sure the testEnvironment configuration option points to an existing node module.

  Configuration Documentation:
  https://jestjs.io/docs/configuration


As of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately.

Follow the instructions and install jest-environment-jsdom:

npm install --save-dev jest-environment-jsdom

This will fix the environment issues.

Canvas

Run your test:

npx jest

You’ll get an error:

Error: Not implemented: HTMLCanvasElement.prototype.getContext (without installing the canvas npm package)

You can either fix this by installing canvas:

npm install --save-dev canvas

Or installing jest-canvas-mock and updating Jest config:

npm install --save-dev jest-canvas-mock
 // jest.config.js
 module.exports = {
+  setupFiles: ['jest-canvas-mock'],
   testEnvironment: 'jsdom',
 };

This will fix the canvas issues.

Spector

Run your test:

npx jest

You’ll get an error:

Cannot find module 'phaser3spectorjs' from './node_modules/phaser/src/renderer/webgl/WebGLRenderer.js'

You can either fix this by installing phaser3spectorjs:

npm install --save-dev phaser3spectorjs

Or mocking the module with Jest:

mkdir -p __mocks__ && echo 'module.exports = {};' > __mocks__/phaser3spectorjs.js

Your test should now pass!

npx jest


Please support this site and join our Discord!