1

I'm using HJSON in a create-react-app project (see answer here), but Jest doesn't use the same webpack configuration, so fails to import HJSON properly - e.g.

import options from '../assets/options.hjson'; 

just sets options to the string '../assets/options.hjson'.

So how can you import an HJSON file using Jest?

Brian Burns
  • 20,575
  • 8
  • 83
  • 77

1 Answers1

1

You need to make a transformer module for Jest to convert the HJSON to JSON - see the docs here.

Make a file jest-hjson-transformer.js in your root directory with

const hjson = require('hjson');

function process(src, path, config, transformOptions) {
  const json = hjson.parse(src);
  const jsonStr = JSON.stringify(json, null, 2);
  const out = `module.exports = ${jsonStr}`;
  return out;
}
exports.process = process;

And in your package.json,

  "jest": {
    "moduleFileExtensions": [
      "js",
      "jsx",
      "hjson"
    ],
    "transform": {
      "^.+\\.hjson$": "<rootDir>/jest-hjson-transformer.js"
    }
  },
Brian Burns
  • 20,575
  • 8
  • 83
  • 77