ccordon
ccordon

Reputation: 1102

Issue with Jest during the unit tests - getContext() is not implemented

When I ran my unit tests I found that I get the following error:

Error: Not implemented: HTMLCanvasElement.prototype.getContext 
(without installing the canvas npm package)

Upvotes: 2

Views: 5514

Answers (3)

Xiao Yu
Xiao Yu

Reputation: 1

If you only get one function error for HTMLCanvasElement, you can simply mock that function when setting up jest:

In setup file as mentioned in above answers, mock the function showing error:

HTMLCanvasElement.prototype.getContext = () => {};

Upvotes: 0

Mohamed Raza
Mohamed Raza

Reputation: 174

the ANSWER for this question helped me to fix the issue with minimum knowledge. i write this answer how I resolve the issue using the official doc DOC

Package.json that I have is as follows

 "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test:unit": "vue-cli-service test:unit --watch",
    "test:e2e": "vue-cli-service test:e2e",
    "lint": "vue-cli-service lint"
  },

under the projects folder, I have another folder named tests where I write end2end test and unit test. on that test folder, i created a file name setup.js where I import necessary modules as follows

import Vue from "vue";
import Vuetify from "vuetify";
import axios from "axios";
import globalVariables from "../src/helper/globalVariables";
import globalFunctions from "../src/helper/globalFunctions";
Vue.use(Vuetify);
Vue.config.productionTip = false;
Vue.prototype.$http = axios;
Vue.prototype.$gv = globalVariables;
Vue.prototype.$gf = globalFunctions;

under my project folder, I have a file named jest.config.js where I set up the setup.js file to test the units. the file jest.config.js possesses the following codes

module.exports = {
  preset: "@vue/cli-plugin-unit-jest",
  verbose: true,
  reporters: [
    "default",
    [
      "./node_modules/jest-html-reporter",
      {
        pageTitle: "VGC Unit Test",
      },
    ],
  ],
  setupFiles: ["jest-canvas-mock", "./tests/setup.js"],
};

include the below line of the code inside your jest.config.js and define the path of your setup.js file

setupFiles: ["jest-canvas-mock", "./tests/setup.js"]

this will solve the issue Error: Not implemented: HTMLCanvasElement.prototype.getContext (without installing the canvas npm package)

Upvotes: 0

ccordon
ccordon

Reputation: 1102

To solve this issue first its necessary to install jest-canvas-mock you can use yarn or npm.

yarn add -D jest-canvas-mock

And then add this into your jest.config.js or the jest configuration section inside the package.json.

setupFiles: [
    'jest-canvas-mock',
    '<rootDir>/config/jest/setupFiles'
  ]

Upvotes: 2

Related Questions