How do you approach mocking Phaser objects in unit tests?

I’m new to Phaser and working in TypeScript. Considering the large size of the Phaser API, I’m wondering how people approach writing unit tests against objects that use it. Looking through all of the example code, I’m not seeing anything that was written with unit testing in mind.

Consider this object pulled from the Snake example:

var Snake = new Phaser.Class({

    initialize:

    function Snake (scene, x, y)
    {
        ...
        this.body = scene.add.group();
        this.head = this.body.create(x * 16, y * 16, 'body');
        this.head.setOrigin(0);
        ...
    },

If I want to represent this as a TypeScript class, I’ll need to pass in something that represents Phaser.Scene. And if I was to use a real Scene object, it’d need a window context to run it in. My instinct here is to mock Scene, but it’ll be very tedious to get around the type constraints.

How do people generally solve this problem? Are there common patterns that this community follows in order to deal with this?

1 Like

I can only say that my game projects are usually so small plus there’s only one developer (me) so unit tests are more trouble than they’re worth TBH.

I just run tests in the browser with the real Phaser.

There’s probably a way to do it in Node with fake canvas.

This isn’t exactly answering your question, but have you tried to separate as much logic from the phaser code as possible? For example, you could make a generalized pathfinding algorithm with unit tests, and then make a thin wrapper around it to connect it to phaser (or a thin wrapper around phaser, whatever). Even if you were able to mock out all the parts of phaser you touch, assuming you didn’t make any mistakes (unlikely, we’re all human) it would become wrong in the next version as the api changed. Just not worth it unless you only need to mock out a couple objects IMO.

Then again, you could get your test to actually run phaser in a browser and check some end condition. This is super slow and potentially unreliable though… Depends on the kind of game and how long it’s going to be updated and maintained I guess

1 Like