Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
         |       ^
like image 236
Dmitry Mahliui Avatar asked Jul 05 '19 10:07

Dmitry Mahliui


People also ask

Is jest enough for testing?

Despite what many may think, Jest is not just a test runner—it is a complete testing framework that has brought testing to another level. It's powerful but easy to use, so give it a try.

Can jest be used for unit testing?

Jest was created by Facebook engineers for its React project. Unit testing is a software testing where individual units (components) of a software are tested. The purpose of unit testing is to validate that each unit of the software performs as designed. A unit is the smallest testable part of any software.

Is jest a testing tool?

Jest is a JavaScript testing framework designed to ensure correctness of any JavaScript codebase. It allows you to write tests with an approachable, familiar and feature-rich API that gives you results quickly. Jest is well-documented, requires little configuration and can be extended to match your requirements.


1 Answers

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'
like image 110
hurricane Avatar answered Oct 11 '22 07:10

hurricane