【问题标题】:Issue with Jest during the unit tests - getContext() is not implemented单元测试期间 Jest 的问题 - 未实现 getContext()
【发布时间】: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


    【解决方案1】:

    要解决这个问题,首先需要安装jest-canvas-mock,你可以使用yarn或npm。

    yarn add -D jest-canvas-mock
    

    然后将其添加到您的 jest.config.jspackage.json 内的开玩笑配置部分。

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

    【讨论】:

    • Stack Overflow 上有几个问题可以通过“只需安装 jest-canvas-mock 以及如何执行 'setupFiles'”来回答。如果这些答案包括一个完整的示例测试,那将非常有帮助......只是一个简单的测试就可以了,但显示 如何 jest-canvas-mock 的使用。
    【解决方案2】:

    这个问题的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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 2018-12-28
      • 2018-06-03
      相关资源
      最近更新 更多