【发布时间】:2020-08-05 00:29:02
【问题描述】:
当我运行单元测试时,我发现我收到以下错误:
Error: Not implemented: HTMLCanvasElement.prototype.getContext
(without installing the canvas npm package)
【问题讨论】:
标签: typescript visual-studio-code jestjs html5-canvas jsdom
当我运行单元测试时,我发现我收到以下错误:
Error: Not implemented: HTMLCanvasElement.prototype.getContext
(without installing the canvas npm package)
【问题讨论】:
标签: typescript visual-studio-code jestjs html5-canvas jsdom
要解决这个问题,首先需要安装jest-canvas-mock,你可以使用yarn或npm。
yarn add -D jest-canvas-mock
然后将其添加到您的 jest.config.js 或 package.json 内的开玩笑配置部分。
setupFiles: [
'jest-canvas-mock',
'<rootDir>/config/jest/setupFiles'
]
【讨论】:
这个问题的ANSWER 帮助我用最少的知识解决了这个问题。我写这个答案我是如何使用官方文档DOC解决问题的@
我拥有的Package.json如下
"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"
},
在项目文件夹下,我有另一个名为 tests 的文件夹,我在其中编写 end2end 测试和单元测试。在那个测试文件夹上,我创建了一个文件名setup.js,我在其中导入了必要的模块,如下所示
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;
在我的项目文件夹下,我有一个名为 jest.config.js 的文件,我在其中设置了 setup.js 文件来测试单元。文件jest.config.js拥有如下代码
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"],
};
在您的jest.config.js 中包含以下代码行并定义您的setup.js 文件的路径
setupFiles: ["jest-canvas-mock", "./tests/setup.js"]
这将解决问题Error: Not implemented: HTMLCanvasElement.prototype.getContext (without installing the canvas npm package)
【讨论】: