Trying to write a typescript transformer for ts-jest

Viewed 346

I am working on a project that uses nextJS. NextJs will inject the react import statement into react components that omit it. This project is also using jest and ts-jest for testing. Tests fail because of the missing react import in the module under test and the modules that module imports. My solution is to write a typescript transformer to inject the react import, which you can provide in the jest.config.js file. Here is my transformer,

const {
 createImportDeclaration,
 createImportClause,
 createIdentifier,
 createLiteral,
 isImportDeclaration,
 updateSourceFileNode,
 visitNode,
} = require('typescript');

function createVisitor(sf, _) {
 // console.log('********pre transform******\n', sf);
 const hasReactImport = (node) => {
   const nodeText = node.getText(sf);
   const isReactImport = isImportDeclaration(node) && nodeText.includes('react');

   let result = isReactImport;

   node.forEachChild((child) => {
     result = result || hasReactImport(child);
   });

   return result;
 };

 const injectReactImport = () => {
   return updateSourceFileNode(sf, [
     createImportDeclaration(
       /*decorators*/ undefined,
       /*modifiers*/ undefined,
       createImportClause(createIdentifier('React'), undefined),
       createLiteral('react')
     ),
     ...sf.statements,
   ]);
 };

 return (node) => {
   if (hasReactImport(node)) return sf;

   const file = injectReactImport();

   console.log('********post transform******\n', file.imports);

   return file;
 };
}

function factory() {
 return (ctx) => (sf) => visitNode(sf, createVisitor(sf, ctx));
}

module.exports = { factory };

This line that has

console.log('********post transform******\n', file.imports);

prints out the imports of the file, but it prints out the same imports that were already present before the transform. I am not getting any errors. Not sure what I am doing wrong.

0 Answers
Related