How would setup unit testing for a plugin?

Hi there!

I’d like to use mocha and chai to write tests for a global plugin that provides fairly self-contained functionality, ideal for unit testing. How would I go about even instantiating the plugin in the context of the unit test? Can I mock the required pluginManager somehow?

Does anybody have experience with unit testing Phaser applications and/or useful links or examples on the topic? Thank you!

After a little digging, I found out the following things (before finding a solution, see down below):

  • Instantating a global plugin (using new) works just fine with null as pluginManager
  • For a class to extend Phaser.Plugins.BasePlugin one has to, unsurprisingly, import phaser
  • Importing Phaser in the unit testing context does not work, since the unit testing context is missing the window object, and Phaser would very much like to monkey patch things in there
  • Including jsdom in the unit testing context is not super straightforward and I soon aborted that endeavour; it also seems to go against the idea of unit testing to emulate the DOM for the testing suite

So after a little more digging, I’ve found a workable solution without additional dependencies:

Create a new intermediate base class for all global plugins

TestablePlugin.js
if (!global.Phaser) {
    // @ts-ignore
    global.Phaser = {}
    // @ts-ignore
    global.Phaser.Plugins = {}
    // @ts-ignore
    global.Phaser.Plugins.BasePlugin = class { constructor(_) { } }
}

class TestableBasePlugin extends Phaser.Plugins.BasePlugin { }

export { TestableBasePlugin }
MyPlugin.js
import { TestableBasePlugin } from "./TestablePlugin"

class MyPlugin extends TestableBasePlugin {
    ...
}

export { MyPlugin }
test.js
import { MyPlugin } from '../src/plugins/MyPlugin'

describe('Test MyPlugin', () => {
    const pluginManager = null
    const myPlugin = new MyPlugin(pluginManager)
    ...
})

This works both in the main application and within the test runner.

FWIW: I’m using the Phaser 3 Parcel Template by ourcade as base for my project, which uses ES6 style modules and imports. Therefore, for mocha to work, I had to add esm as a dev dependency and run mocha with the command mocha -r esm.

1 Like