Dmitry Mahliui
Dmitry Mahliui

Reputation: 93

How to set up jest for testing canvas

Can't run jest tests with canvas. I have functions that's work with canvas, context, dom etc. How to set up jest correctly for that?

I have tried to use jest-canvas-mock, but how to install it correctly?

package.json

"devDependencies": {
    ***
    "jest": "^24.8.0",
    "jsdom": "^15.1.1",
    ***
  },
  "dependencies": {
    ***
  },
  "jest": {
    "setupFiles": [
      "jest-canvas-mock"
    ]
  }
}

jest.config.js

module.exports = {
  roots: [
    '<rootDir>/src',
  ],
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$',
  moduleFileExtensions: [
    'js',
  ],
};

console.log:

 TypeError: Cannot set property 'imageSmoothingEnabled' of null

      15 |       const canvas = document.createElement('canvas');
      16 |       const context = canvas.getContext('2d');
    > 17 |       context.imageSmoothingEnabled = false;
         |       ^

Upvotes: 6

Views: 7539

Answers (1)

hurricane
hurricane

Reputation: 6724

Try to install jest-canvas-mock library into package.json.

npm install --dev jest-canvas-mock

Then import it into your test file.

import 'jest-canvas-mock'

Upvotes: 8

Related Questions