TransWikia.com

Ability to convert a json file to js in Jest

Stack Overflow Asked by Prasad Sawant on December 23, 2021

We are using create-react-app to build our declarative framework. In this framework, we author a json file which gets loaded into a react-component by webpack. We have authored specific loader for that. This works well in the browser. But facing issues with unit testing. Create-react-app uses Jest for unit testing.
What I want to acheive is transform these json files in js or react component, but hitting following limitations

  1. If I add custom transform for json, then it does not work due to restriction put up by jest-runtime.
    Post transformation, it expects the output to be json only. See Jest-runtime code which restricts

enter image description here

  1. If I rename file extensions to ‘.vm’ then it never picks up my transformer as create-react-app add fileTransformer in following cases. The highlighted transformer gets picked up for all other types mentioned in that regex.

enter image description here

Need your guidance to resolve this issue.

One Answer

Webpack Docs: https://webpack.js.org/loaders/json5-loader/ The Config for conversion of JSON to JS would look something like this. Then you could pass it into Jest rather than have Jest try to convert it during runtime.

module.exports = {
  module: {
    rules: [
      {
        test: /.json5$/i,
        loader: 'json5-loader',
        type: 'javascript/auto',
      },
    ],
  },
};

Answered by Jacob on December 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP