当我运行单元测试时,我发现我得到了以下错误:
Error: Not implemented: HTMLCanvasElement.prototype.getContext
(without installing the canvas npm package)
要首先解决这个问题,必须安装jest-cavas mock,您可以使用yarn或npm。
yarn add -D jest-canvas-mock
然后将其添加到jest.config.js
或package.json
内的jest配置部分。
setupFiles: [
'jest-canvas-mock',
'<rootDir>/config/jest/setupFiles'
]
我的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"
},
在projects文件夹下,我有另一个名为tests的文件夹,我在其中编写end2endtest和unit test。在这个测试文件夹上,我创建了一个名为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
文件来测试单元。文件CCD_ 7具有以下代码
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)
问题
如果HTMLCanvasElement只有一个函数错误,那么在设置jest:时可以简单地模拟该函数
在上述答案中提到的设置文件中,模拟显示错误的函数:
HTMLCanvasElement.prototype.getContext = () => {};