Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest preprocessor for Typescript/ES6

I am trying to test A Typescript Class Using Jest. Since I need to use es6's async/await I need the typescript class to be compiled to es6 first and then to es5 using babel. What do I need to add to the preprocessor in order to achieve this. My current preprocessor looks like this:

const tsc = require('typescript');

module.exports = {
    process: function(src, path) {
        if (path.endsWith('.ts') || path.endsWith('.tsx')) {
            return tsc.transpile(
                src,
                {
                    module: tsc.ModuleKind.CommonJS,
                    jsx: tsc.JsxEmit.React
                },
                path,
                []
            );
        }
        return src;
    }
};

Do I need to add target: tsc.ScriptTarget.ES6? When I do so I get an unexpected identifier = error in the processed code which looks like the transpiled version of my .ts class. What I gathered from this is that my preprocessor is compiling data to es6 but my es6 is not being transpiled to es5. Also is there any readymade preprocessor which can do this?

like image 446
Nahush Farkande Avatar asked Jan 05 '23 16:01

Nahush Farkande


1 Answers

If you're looking for a custom config, this might be your answer: https://stackoverflow.com/a/40070453/4909970

However, in my experience ts-jest works fine. Just make sure you specify jest settings for ts-jest "target": "ES6" in __TS_CONFIG__ or just add your current typescript config.

You package.json will look somethings like this:

"jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/ts-jest/preprocessor.js",
    "globals": {
        "__TS_CONFIG__": "tsconfig.json"
    }
}
like image 116
pavloko Avatar answered Jan 18 '23 01:01

pavloko