2

I've been trying to set up jest as a test framework for a project I'm working on that uses Phaser, and I am getting stuck trying to mock out Phaser itself. I first ran into this issue with the missing canvas, which I was able to resolve from the link. But now I am getting another error "Cannot read property 'postion' of undefined".

jest.config.js:

module.exports = {
  verbose: true,
  roots: ['./src'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  moduleNameMapper: {
    '\\.(css|less|scss)$': 'identity-obj-proxy'
  },
  setupFiles: ['jest-canvas-mock']
}

__mocks__/phaser.js:

const phaser = jest.genMockFromModule('phaser');

module.exports = phaser;

error message:

TypeError: Cannot read property 'position' of undefined

      1 | 
    > 2 | const phaser = jest.genMockFromModule('phaser');
        |                     ^
      3 | 
      4 | module.exports = phaser;

      at Image.get [as x] (node_modules/phaser/src/physics/matter-js/components/Transform.js:36:30)
          at Array.forEach (<anonymous>)
          at Array.forEach (<anonymous>)
          at Array.forEach (<anonymous>)
          at Array.forEach (<anonymous>)
          at Array.forEach (<anonymous>)
      at Object.<anonymous> (src/__mocks__/phaser.js:2:21)
      at Object.<anonymous> (src/main.ts:3:1)
      at Object.<anonymous> (src/main.spec.ts:3:1)

I'm looking at that Transform file and its blowing up on a getter because this.body is undefined:

get: function ()
{
  return this.body.position.x;
},

Has anyone else had this problem? I'm hoping I just have some configuration wrong.

bradimus
  • 825
  • 11
  • 25

1 Answers1

0

I wanted to thank you for sharing your configuration to run Jest with Phaser 3.

Regarding your issue, it appears that the Phaser.Physics.Matter.Commponents.Trasnform component is not really compatible with the way jest.genMockFromModule() works.

You can hack it simply by creating a default value for the body property of the Transform instance in phaser/src/physics/matter-js/components/Trasnform.js:

var Transform = {

    body: Body.create({}),

    // ...

Although I don't know how it might affect the production code.

If you don't use the Matter.js physics engine in your game, maybe you could create a custom Phaser 3 build instead.

raaaahman
  • 80
  • 11