Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to test any code using an openlayers' module in Jest

I'm trying to write some tests for some modules that happen to import an openlayers module or two. But as some others have found (here, here, and here), this doesn't work out of the box. Here's what I've tried:

  • renaming .babelrc to babel.config.js and exporting the config
  • added transformIgnorePatterns to my jest.config.js

I'm just at a loss as to what would fix this now.

I'm using:

  • Non-CRA webpack config
  • Jest v23.6.0
  • babel-core 6.26.3
  • typescript 3.1.3
  • ts-jest 22.4.6

Here's my configs:

Jest:

module.exports = {
  setupFiles: [
    "./testConfig/test-shim.js",
    "./testConfig/test-setup.js"
  ],
  transform: {
    "^.+\\.tsx?$": "ts-jest"
  },
  transformIgnorePatterns: [
    "/node_modules/(?!(ol)/).*/",
    "node_modules/(?!(ol)/)",
  ],
  testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx|tsx?)$",
  moduleNameMapper: {
    "^(Controllers|Api|Utilities)/(.*)$": "<rootDir>Scripts/$1/$2"
  },
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
  coverageReporters: ["text", "text-summary", "html"],
  coverageDirectory: "testConfig/coverageReport",
  collectCoverageFrom: ["**/Scripts/{App,Controllers,Utilities,Localization,EntryPoints}/**/*.{ts,tsx}"],
  coverageThreshold: {
    global: {
      branches: 0,
      functions: 0,
      lines: 0,
      statements: 0
    }
  }
};
like image 229
jktravis Avatar asked Dec 10 '18 14:12

jktravis


1 Answers

Got this working, finally. The problem was that the project was using TypeScript and, as usual, that made things far more complicated than it needed to be.

Since the OL sources needed to be compiled, and those files are written in JavaScript, I needed to add another transform to my config to just handle those files. After that, it complained about canvas, so I had to also install a canvas mock.

So the changed portion of my config is as follows:

  setupFiles: [
    "./testConfig/test-shim.js",
    "jest-canvas-mock", // <- the new mock
    "./testConfig/test-setup.js"
  ],
  transform: {
    "^.+\\.tsx?$": "ts-jest",
    "^.+\\.jsx?$": "babel-jest", // <- also compile js/x files
  },
  testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
  transformIgnorePatterns: [
    "node_modules/(?!(ol)/)", // <- exclude the OL lib
  ],

Hope this helps someone else!

like image 70
jktravis Avatar answered Oct 20 '22 20:10

jktravis