单元测试期间Jest出现问题-未实现getContext()



当我运行单元测试时,我发现我得到了以下错误:

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.jspackage.json内的jest配置部分。

setupFiles: [
'jest-canvas-mock',
'<rootDir>/config/jest/setupFiles'
]
这个问题的答案帮助我用最少的知识解决了这个问题。我写下这个答案,我如何使用官方文档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"
},

在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 = () => {};

最新更新