'Vue with jest & jsdom test, TypeError: svg.createSVGPoint is not a function

When I am testing my vue component that use d3js with jest, I got this error

[Vue warn]: Error in mounted hook: "TypeError: svg.createSVGPoint is not a function

I saw on the internet it is due to jsdom that do not support svg functions but they are all posts.

Does it exists a solution to bypass this error?

Here is my test script for information

import Chart from "@/src/components/chart.vue"
import { mount } from "@vue/test-utils.js"

async function factory(data) {
  const propsData = {
    data
  }
  return mount(Chart, {
    propsData
  })
}

describe("chart", () => {
  it("should handle values", async () => {
    const mounted = await factory([
      { name: "serie1", value: 1, date: "2017-01-01" },
      { name: "serie1", value: -5, date: "2017-02-01" }
    ])
    const b1 = mounted.findAll("rect").at(0).element.getBoundingClientRect()
    const b2 = mounted.findAll("rect").at(1).element.getBoundingClientRect()
    expect(b1.y + b1.height).toBeCloseTo(b2.y, 1)
    mounted.destroy()
  })
})

And my test break in my chart.vue component when I am using select from d3-select (I did not paste the whole code to not pollute the post)

import { select } from "d3-selection"
...
 select(this.$refs.drawArea)
...

I have also in my jest.config.js

const esModules = [
  "d3",
  "d3-time-format",
  "d3-array",
  "d3-color",
  "d3-interpolate",
  "d3-selection",
  "d3_exploding_boxplot",
  "internmap"
].join("|")

module.exports = {
  // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
  moduleNameMapper: {
    "@/(.*)$": "<rootDir>/$1",
    "^.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
  },
  moduleFileExtensions: ["js", "ts", "vue"],
  // A map from regular expressions to paths to transformers
  transform: {
    "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
    "^.+\\.ts$": "<rootDir>/node_modules/ts-jest",
    "^.+\\.vue$": "<rootDir>/node_modules/@vue/vue2-jest",
    "^.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
  },
  // Ensure esModules are transformed
  transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
  // The test environment that will be used for testing
  testEnvironment: "jsdom",
  //
  setupFiles: ["<rootDir>/tests/setup.js"],
  setupFilesAfterEnv: ["<rootDir>/tests/setupFilesAfterEnv.js"]
}



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source