How do you use HJSON with Jest in a create-react-app project?

90 Views Asked by At

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?

1

There are 1 best solutions below

0
Brian Burns On

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"
    }
  },