jest-test-module-preprocessor

1.0.0 • Public • Published

jest-test-module-preprocessor

This package aims to simplify requiring module file when testing with Jest

Usage

  1. Run following command in project root

     npm install --save-dev jest-test-module-preprocessor
    
  2. Add following property to your jest config

     {
       "transform": {
         "\\.js$": "<rootDir>/jest/transform.js"
       }
     }
    
  3. Put following code in jest/transform.js

     const preprocessor = require('jest-test-module-preprocessor')();
    
     module.exports = {
       process: (...args) => {
         const transformed = preprocessor.process(...args);
         return transformed;
       },
     };
    
  4. Then you can simplify require the module you intrested when writing test file

     // In <rootDir>/test/a/b/c/d.spec.js
     const d = require('__module__');
    
     // The above statement is same as
     // require('../../../../src/a/b/c/d.js');
    

Configuration

When initializing preprocessor, an optional configuration can be used.

const preprocessor = require('jest-test-module-preprocessor')({
  modulePlaceholder: '__module__',
  srcDir: 'src'
});

Notes about babel-jest

When "transform" is overwritten in any way the babel-jest is not loaded automatically anymore

In order to utilize babel-jest, modify jest/transform.js as following:

const preprocessor = require('jest-test-module-preprocessor')();

const babel = require('babel-jest');

module.exports = Object.assign(
  {},
  babel,
  {
    process: (...args) => {
      const transformed = preprocessor.process(...args);
      const code = babel.process(
        transformed,
        ...args.slice(1)
      );
      return code;
    },
  }
);

Readme

Keywords

Package Sidebar

Install

npm i jest-test-module-preprocessor

Weekly Downloads

1

Version

1.0.0

License

GPL-3.0

Last publish

Collaborators

  • opengg