babel-plugin-transform-comment-to-assert

Replace commented expressions with assert statements


License
MIT
Install
npm install babel-plugin-transform-comment-to-assert@4.1.0

Documentation

babel-plugin-transform-comment-to-assert npm

replace commented expressions with assert statements

Install

$ npm install --save babel-plugin-transform-comment-to-assert

Usage

import * as babel from "@babel/core";
import plugin from "babel-plugin-transform-comment-to-assert";

function replace(code) {
  return babel
    .transform(code, { babelrc: false, plugins: [plugin] })
    .code.replace(/\n/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

replace("1 //=> 1");
//=> 'assert.deepEqual(1, 1);'

Objects:

replace("a = { a: 1 }; a //=> {a: 1}");
//=> 'a = { a: 1 }; assert.deepEqual(a, { a: 1 });'

Results of function calls:

replace("(() => 'foo')() //=> 'bar'");
//=> "assert.deepEqual((() => 'foo')(), 'bar');"

It also supports console.log:

replace("console.log('foo') //=> 'bar'");
//=> "console.log('foo'); assert.deepEqual('foo', 'bar');"

Throws:

replace(`
const a = () => {
  throw new Error('fail');
};
a() // throws Error
`);
//=> `const a = () => { throw new Error('fail'); }; assert.throws(() => a(), Error);`
replace(`
const a = () => {
  throw new Error('fail');
};
a() // throws /fail/
`);
//*=> `const a = () => { throw new Error('fail'); }; assert.throws(() => a(), /fail/);`

License

MIT © Sigurd Fosseng