babel-utils / babel-plugin-tester Goto Github PK
View Code? Open in Web Editor NEWUtilities for testing babel plugins
Home Page: http://npm.im/babel-plugin-tester
License: MIT License
Utilities for testing babel plugins
Home Page: http://npm.im/babel-plugin-tester
License: MIT License
babel-plugin-tester
version: 7.0.1node
version: 10.16.3npm
(or yarn
) version: 1.12.1Relevant code or config
What you did:
Updated babel-plugin-tester from 5 to 7
What happened:
All the snapshots broke because the output is now being compiled to ES5 code
- const ReactNative = require('react-native-web/dist/index');
+ "use strict";
+
+ var ReactNative = require("react-native-web/dist/index");
- const unstable_createElement = require('react-native-web/dist/exports/createElement').default;
+ var unstable_createElement = require("react-native-web/dist/exports/createElement").default;
- const ColorPropType = require('react-native-web/dist/exports/ColorPropType').default;
+ var ColorPropType = require("react-native-web/dist/exports/ColorPropType").default;
- const StyleSheet = require('react-native-web/dist/exports/StyleSheet').default;
+ var StyleSheet = require("react-native-web/dist/exports/StyleSheet").default;
- const View = require('react-native-web/dist/exports/View').default;
+ var View = require("react-native-web/dist/exports/View").default;
- const TouchableOpacity = require('react-native-web/dist/exports/TouchableOpacity').default;
+ var TouchableOpacity = require("react-native-web/dist/exports/TouchableOpacity").default;
- const processColor = require('react-native-web/dist/exports/processColor').default;
+ var processColor = require("react-native-web/dist/exports/processColor").default;
Reproduction repository:
https://github.com/necolas/react-native-web/
Problem description:
I want the snapshots not to change to compiled output
babel-plugin-tester
version: 7.8.3node
version: v12.14.0npm
(or yarn
) version: [email protected]When using the declare(...)
helper from @babel/helper-plugin-utils
, the api.assertVersion(...)
call gives me the following error:
● Test suite failed to run
Requires Babel "^7.0.0-beta.41", but was loaded with "7.8.4". You'll need to update your @babel/core version.
18 | export default declare((api, options, dirname) => {
19 | // check babel version
> 20 | api.assertVersion(7);
If you look at the error message, my @babel/core
version is ahead of the minimum requirement. I believe this is the result of some incompatibility between the declare(...)
helper and this library.
This message is not displayed if I switch to running my tests with @babel/helper-plugin-test-runner
.
Please let me know if there's any additional information I can provide you with.
babel-plugin-tester
version: 5.4.0node
version: 9.8.0npm
(or yarn
) version: 5.6.0Relevant code or config
const pluginTester = require('babel-plugin-tester')
const myPlugin = require('./plugin')
pluginTester({
plugin: myPlugin,
filename: __filename,
tests: [{
fixture: '__fixtures__/1/from.js',
outputFixture: '__fixtures__/1/to.js'
}],
babelOptions: {
babelrc: true
}
})
What you did:
I ran jest using jest test.js and the test failed, like it should, but I was expecting the usual diff showing what it got and what it expected, but only the following output appeared. Am I doing something wrong or does it only show that message?
What happened:
FAIL ./test.js
ast-transform
✕ 1. ast-transform (57ms)
● ast-transform › 1. ast-transform
AssertionError [ERR_ASSERTION]: Output is incorrect.
at tester (node_modules/babel-plugin-tester/dist/index.js:206:28)
at Object.<anonymous> (node_modules/babel-plugin-tester/dist/index.js:114:13)
at step (node_modules/babel-plugin-tester/dist/index.js:43:191)
at node_modules/babel-plugin-tester/dist/index.js:43:361
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 1.49s
Ran all test suites matching /test.js/i.
babel-plugin-tester
version:^5.4.0node
version:v8.5.0npm
(or yarn
) version:5.3.0Relevant code or config
var codeStr = "var a = 1";
var pluginTester = require('babel-plugin-tester')
var plugin = require("../lib/index")
pluginTester({
plugin: plugin,
tests: [
codeStr
]
})
What you did:
I just use pluginTester to test my plugin and error happened.Should I install some other plugin?
Reproduction repository:
Problem description:
Suggested solution:
babel-plugin-tester
version: v5.0.0node
version: N/anpm
(or yarn
) version: N/aWhat you did:
Tried to parse typescript using babel 7.
What happened:
It would not parse typescript.
Problem description:
Basically this npm package imports babel-core
, but it was renamed to @babel/core
in babel 7.
Suggested solution:
Possibly create a branch for babel 7 that imports @babel/core
instead of babel-core
and publish an alpha/beta of a new major version on the next
npm channel from this branch.
When I test my plugin width babel-plugin-tester, I found the output and expected were only have difference of space. Could you tell me how to ignore the diff caused by space? THX.
babel-plugin-tester
version: 9.0.1node
version: 14.3.0npm
(or yarn
) version: 1.22.4Relevant code or config
import pluginTester from 'babel-plugin-tester/pure';
import * as path from 'path';
import plugin from 'babel-plugin-macros';
pluginTester({
plugin,
babelOptions: {
plugins: [
[
'babel-plugin-module-resolver',
{
alias: {
'@material-ui/utils': path.resolve(__dirname, '../src'),
},
},
],
],
},
filename: __filename,
fixtures: path.resolve(__dirname, './__fixtures__'),
tests: [
{
title: 'can throw on missing error codes',
error: /unknown: Missing error code for message 'missing'. Did you forget to run `yarn extract-errors` first?/,
code: `
import MuiError from '@material-ui/utils/MuiError.macro';
throw new MuiError('missing');`,
pluginOptions: {
muiError: {
missingError: 'throw',
},
},
},
],
});
What you did:
babel-plugin-module-resolver
in babelOptions.plugins
What happened:
Tests in tests
pass since babel-plugin-module-resolver
is applied before the plugin
.
Tests in fixtures
fail because babel-plugin-module-resolver
is not applied before plugin
/home/eps1lon/Development/projects/mui/fork/packages/material-ui-utils/test/__fixtures__/literal/code.js: Cannot find module '@material-ui/utils/MuiError.macro' from '/home/eps1lon/Development/projects/mui/fork/packages/material-ui-utils/test/__fixtures__/literal'
Reproduction repository:
yarn
yarn cross-env NODE_ENV=test mocha packages/material-ui-utils/test/MuiError.macro.test.js --watch
Problem description: I want to write the test that mirror actual usage. For babel macros I would need to use a different import source than what is actually used.
Suggested solution:
babelOptions.plugins
firstbabelOptions.plugins
last but add an option so that we can configure it (either flag "applyFirst" or custom merger function)It would be nice to be able to use this tool for things other than plugins easily.
Right now I do stuff like this:
import pluginTester from 'babel-plugin-tester';
import printAST from 'ast-pretty-print';
import lib from './';
const plugin = () => {
return {
name: 'test-plugin',
visitor: {
Program(path) {
let result = lib(path);
let printed = printAST(result);
path.pushContainer(
'body',
t.expressionStatement(t.templateLiteral([
t.templateElement({ raw: printed }, true)
]))
);
},
},
};
};
babelTester({
plugin,
snapshot: true,
tests: [...]
});
But it'd be nice if I could get something lower level where I can just call a function on a Babel File and the returned result would get printed via ast-pretty-print for snapshotting.
babelTester({
name: 'util',
snapshot: true,
fn: file => {
return lib(file.path);
},
tests: [...]
});
babel-plugin-tester
version: 10.1.0node
version: v18.8.0npm
(or yarn
) version: 4.0.0-rc.13Relevant code or config
import pluginTester from "babel-plugin-tester";
import { PluginPass } from "@babel/core";
pluginTester({
plugin: babelPlugin,
filename: 'testing.ts', // <-- doesn't seem to propagate to `state.filename` - it's probably not the right option for this I assume
tests: [{ code: "'hello';" }],
});
const babelPlugin = function babelPlugin(): {
visitor: Visitor<PluginPass>;
} {
return {
visitor: {
Identifier(path, state) {
console.log(state.filename);
}
}
}
}
What you did:
I'm trying to test out how to use state.filename
inside of a plugin and how I can set it in the test code.
What happened:
I'm getting an error since the state.filename
variable is by default undefined
and I have not found a way to add it via the test.
Problem description:
I've tried solving this by setting the filename
option (not sure if that's the correct one) but it did not work. I have also thought about using one of the wrapper options (I'm not sure what they do so, so far no luck 😅)
When using fixtures it would be nice if it was possible to provide plugin options in a options.json
file.
This would make it easier to test different features of a plugin, where different settings can be provided.
babel-plugin-tester
version: 8.0.1node
version: v12.14.1yarn
version: 1.21.1Relevant code or config
const pluginTester = require("babel-plugin-tester");
pluginTester({});
What you did:
Ran the jest
.
What happened:
TypeError: pluginTester is not a function
Problem description:
"devDependencies": {
"babel-plugin-tester": "8.0.1",
"jest": "^25.1.0",
"prettier": "^1.19.1"
}
and run jest
It fails with the error above. (all other non-babel tester tests are green)
If I return back to version 7 it works fine. Have no idea what is wrong TBH :)
If I try to return jest to version 23 and 24 from 25, result is still the same. So probably some wrong babel compilation of source code of version 8? Have no idea TBH.
Suggested solution:
¯\_(ツ)_/¯
babel-plugin-tester
version: 9.0.1
node
version: 10.16.3
npm
(or yarn
) version: [email protected]
What you did:
Wrote code in the plugin that will throw an error if it is reached
What happened:
Test fails without the code path that throws an error being able to be tested correctly
Reproduction repository:
N/A
Problem description: If your babel plugin can enter a code path where it throws an error, I'm unsure how to test that code path
Suggested solution: Unsure right now
I am struggling to test a case where another plugin is changing the resolveModuleSource
babel option. It seems that on options merge, plugins from a fixture .babelrc
file are appended after the tested plugin. See below.
babel-plugin-tester
version: 3.3.0node
version: 8.2npm
(or yarn
) version: yarn 0.27.5Relevant code or config (.babelrc
from fixtures)
{
"plugins": [["./custom_resolver.js", { "foo": "bar" }]]
}
What you did:
I created a test with the following option: babelOptions: { babelrc: true },
What happened:
The custom babel config was loaded, but plugins were added after the SUT, whereas I needed them to be loaded before the SUT.
Reproduction repository:
See real34/tmp-babel-plugin-inline-import-graphql-ast@29ee949
You can checkout the sample repo and run yarn test
to reproduce the error. It should generate a snapshot file without any error (the error is due to plugins sort order, which causes https://github.com/real34/tmp-babel-plugin-inline-import-graphql-ast/blob/29ee949fb817615bd61553d01e55af11baf2d19f/index.js#L20 to not be executed with the correct module resolver)
Suggested solution:
It would be great to provide/document a way to create a .babelrc
file where the plugin and its options could be inserted anywhere in the plugins definitions. Or at least how to configure plugins to be run before the SUT.
The simplest solution I can think of would be to prepend plugins definition in
babel-plugin-tester/src/index.js
Line 213 in 6085c16
babelPreviousPlugins
for instance)... but it feels a bit hacky no?
Another solution for my use case would be to support .babelrc.js
files (see babel/babel#4630), which may allow here to define a custom source resolver
babel-plugin-tester
version: 11.0.4node
version: 19.5.0npm
(or yarn
) version: pnpm 7.26.0Relevant code or config
pluginTester({
plugin: babelPluginJsxAssetUrlImport,
fixtures: path.join(__dirname, 'fixtures'),
babelOptions: {
plugins: ['@babel/plugin-syntax-jsx']
}
});
Problem description:
I create a simple fixture, then tormented by semicolons and blank lines. like this:
In fact the two files are exactly the same
Suggested solution:
before run expect, maybe should format output file
use prettier.
babel-plugin-tester
5.0.0:node
8.7.0:npm
5.4.2:Relevant code or config
const pluginTester = require('babel-plugin-tester');
// normally you would import this from your plugin module
function identifierReversePlugin() {
return {
name: 'identifier reverse',
visitor: {
Identifier(idPath) {
idPath.node.name = idPath.node.name.split('').reverse().join('')
},
},
}
}
pluginTester({
plugin: identifierReversePlugin,
snapshot: true,
tests: [
{code: '"hello";', snapshot: false},
{
code: 'var hello = "hi";',
output: 'var olleh = "hi";',
},
`
function sayHi(person) {
return 'Hello ' + person + '!'
}
console.log(sayHi('Jenny'))
`,
],
})
What you did:
Run the sample code from the docs
What happened:
Throws with:
return describe(describeBlockTitle, function () {
^
ReferenceError: describe is not defined
It's possible to return metadata from the babel file transform result with a plugin. Is there a feature that can be used in the plugin tester to extract the metadata?
const babelFileResult = transform();
console.log('code', babelFileResult.code);
console.log('metadata, babelFileResult.metadata);
If not, would it be possible to have a feature that matches the returned metadata somehow?
This metadata can be set with a plugin and can return some useful information such as when the plugin is trying to extract some infomation from the source code while transforming it
It'd be nice if this util could capture errors
{
title: 'test',
code: 'code',
// one of
error: true,
error: 'Expected Error Message',
error: /test on error/,
error: SyntaxError,
error: err => /foo/.test(err) && err instanceof SyntaxError,
},
```'
Or:
```js
{
title: 'test',
code: 'code',
snapshot: true,
error: true,
},
It'd be nice to be able to configure test.only
or test.skip
:
{
title: 'not working yet',
...
skip: true,
},
{
title: 'currently focused on',
...
only: true,
},
babel-plugin-tester
version: 8.0.0, 8.0.1node
version: 10.18.1npm
(or yarn
) version: 6.13.6 (npm
)Relevant code or config:
Dummy plugin using api.assertVersion
.
const { declare } = require("@babel/helper-plugin-utils");
const plugin = declare(({ assertVersion }) => {
assertVersion(7);
return { name: "dummy-plugin" };
});
What you did:
Execute tests.
What happened:
Requires Babel "^7.0.0-beta.41", but was loaded with "7.7.2". You'll need to update your @babel/core version.
Attempting to infer the name of your plugin failed. Tried to invoke the plugin which threw the error.
Reproduction repository:
babel-plugin-remove-template-literals-whitespace
Problem description:
Issue lies in getPluginName method, which has exactly same issue as is mentioned here. This method instantiate provided plugin with exports of @babel/core obtained in pluginTester method.
As a hotfix, api.assertVersion
method in passed babel reference can be overloaded with noop only in getPluginName method.
name = plugin(/* api = */ Object.assign({}, babel, { assertVersion: noop }), /* options = */ {}, /* dirname = */ "").name;
But still, a proper fix will be required.
Suggested solution:
Not sure.
Hello
I'm using babel-plugin-tester
to test a Babel plugin I am working on. (Great tool BTW; thanks for sharing this.)
My tests were failing for no apparent reason. Then I realize that the following line of code was returning an error because of a difference with the line feed \r\n
vs \n
.
I fixed the problem by replacing the following line of code:
assert.equal(actual, output, 'actual output does not match output.js')
... with this ...
const normalizeNewline = require('normalize-newline');
assert.equal(normalizeNewline(actual), normalizeNewline(output), 'actual output does not match output.js')
since you're using async function here and didn't use babel-plugin-transform-runtime.
Maybe set the target of env
preset to 6
or add transform-regenerator
to blacklist?
babel-plugin-tester
version:5.5.2node
version: v8.11.2npm
(or yarn
) version: [email protected]What you did:
I have a fixture setup with an input/output code file and the following test configuration.
What happened:
On error the messaging is very generic and doesn't clue into the failure.
Screenshot of fixture input/output error:
Reproduction repository:
I don't have one at this point that is public.
Problem description:
Error is not descriptive doesn't help point the user to resolution.
Suggested solution:
I know that snapshots look better since that functionality is built into jest. I think we should be able to use similar logic to find the difference between the 2 files contents.
Hello! After nearly two years, the 11.0.0 version of babel-plugin-tester has been released 🎉🎉, and with it comes a bevy of improvements bringing the project up to date with the latest and greatest in the JavaScript ecosystem:
@types/babel-plugin-tester
package)node:test
, and Jasmine support with documented examplesTo ensure as smooth an experience as possible, preserving backwards compatibility was a priority for this release. The vast majority of babel-plugin-tester users should be able to migrate to the latest version without incident. However, if you notice any BC-breaking changes or have any questions or suggestions, feel free to leave a comment here or, if you encounter a problem, open a new issue.
I'll keep this issue pinned until the next minor release. Happy testing!
I'm having an issue when doing:
babelOptions: {
// doesn't work
babelrc: true
},
This results in an unexpected token error as my test is attempting to parse code that requires multiple babel presets to parse (its a react component). This can easily be fixed by supplying the presets directly in the test config, or by adding the extends option like so:
babelOptions: {
// this works
presets: ["es2015", "stage-0", "react"],
// this works too
extends: path.resolve(__dirname, '..', '.babelrc'),
},
I'm wondering if I'm missing something here in regards to preferred approach when using a .babelrc? Looking through the code I don't see any logic around the babelrc
boolean so I am unsure as to the desired experience here.
I would be happy to PR a fix if this indeed a bug, or update the documentation if I'm just missing something here. Thanks for this tool, it's super useful 👍
per the babel contributing docs and the generator-babel-plugin fixtures (for example), I think it would be really handy to support a fixturesDirectory
which would do basically this
plugin
and pluginName
are plugin-centric.
I would like to test a preset which bundle a couple of plugins.
Could you please document how to do that (if it's possible)?
Hello!
First, thanks so much for this awesome package, it has saved me hours of dev time! I've been using it to develop a dozen little babel plugins that do various things for my projects, but I've run into some difficulties using it. My strategy has been to copy-paste some on-the-fly fixes between projects which is not ideal, so I went ahead and bundled these fixes/features together into my own babel-plugin-tester fork which my team and I have been using successfully for a little while.
Today, I feel confident enough to contribute these fixes back upstream and hopefully retire the fork. They are:
only
, skip
, and title
test options in fixturesAdditional details are in each PR. With the exception of #91 (which relies on #88), each PR is self-contained and doesn't rely on merging the others, so they can be modified, rejected, or accepted as desired. I also submitted a PR that combines these other six PRs together since the octopus merge strategy can't do it effectively.
Thanks again for this package!
babel-plugin-tester
version: 10.0.0
node
version: v14.7.0
npm
(or yarn
) version: 1.22.10
Relevant code or config
What you did:
Write an asynchronous babel plugin.
What happened:
You appear to be using an async plugin/preset, but Babel has been called synchronously
Reproduction repository:
Problem description:
babel-plugin-tester
doesn't support asynchronous plugins (introduced in 7.13.0) because it calls babel.transform
synchronously here, and babel.transformSync
here.
Suggested solution:
Check for the existence of babel.transformAsync
and use that, or fallback to synchronous call to babel.trasnform
. Happy to make a PR if this is an acceptable solution!
Hi,
this is more a question than a bug report - I'm pretty sure I'm missing something fairly obvious.
I'm trying to write a babel plugin that analyses typescript files, so I was trying to write a simple test file that analyses some code and prints out the typescript definition.
import pluginTester from "babel-plugin-tester";
pluginTester({
plugin: identifierReversePlugin,
snapshot: true,
tests: [
{
code: `
import React from 'react'
interface Test {
name: string;
}
const User: React.FC<Test> = () => {
return null;
}
`,
snapshot: true,
},
],
});
function identifierReversePlugin() {
return {
name: "analyse ts",
visitor: {
Identifier(idPath) {
console.log(idPath);
},
},
};
}
However, when I run the test it throws the error
SyntaxError: unknown: Unexpected reserved word 'interface'. (3:0)
1 | import React from 'react'
2 |
> 3 | interface Test {
| ^
4 | name: string;
5 | }
6 |
I've tried to google my way through it but whatever I try, the error persists.
Would love some pointers on getting this to run :)
Best
babel-plugin-tester
version: ^9.1.0node
version: v12.16.3yarn
version: 1.19.1folder structure (some files ommited):
ROOT
|-- package.json
|-- src
|-- __tests__
| |-- __fixtures__
| | |-- firstTest
| | | \-- code.ts
| | \-- secondTest
| | \-- code.ts
| \-- index-test.ts
\-- index.ts
content of src/__tests__/index-test.ts
file:
import pluginTester from "babel-plugin-tester";
import * as path from "path";
import plugin from ".."; // my babel plugin
pluginTester({
plugin,
pluginName: "plugin",
endOfLine: "crlf",
babelOptions: {
presets: ["@babel/preset-env", "@babel/preset-typescript"],
plugins: [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-export-default-from",
"@babel/proposal-object-rest-spread",
],
},
filename: __filename,
fixtures: path.join(__dirname, '__fixtures__'),
});
What you did:
run jest via 'yarn test' command ("test": "jest" in package.json)
What happened:
test run succesfully and created files __fixtures__/*/output.ts
Problem description:
output files have .ts
extension because source files are written in typescript, but theyre actually transpiled javascripts, so they should have .js
extension.
Suggested solution:
add option to speicfy output file extension:
fixtureOutputExt?: string | (test: string) => string
where:
string
: all output files use this extension(testName: string) => string
: projection 'test name' to output extension: name => name === "firstTest" ? ".jsx" : ".js";
Hi.
I'm trying to write a babel plugin that transforms one decorator into a different one. For instance transform
class MyClass {
@injectIfEnabled('FEATURE') router
}
into
class MyClass {
@inject router
}
when that feature is enabled or into
class MyClass {
@inject router
}
when it's not.
I'm running these:
babel-plugin-tester
9.2.0:node
14:npm
(or yarn
) version: 6.14The problem I'm facing is that since my plugin looks for class properties with a decorator named injectIfEnabled
, I need the plugin to run before @babel/plugin-proposal-decorators
has transpiled decorators.
I can't seem to find a way of specifying that the plugin under testing must run in a specific order:
pluginTester({
plugin: myPlugin,
pluginName: 'my-plugin',
babelOptions: {
plugins: [
['@babel/plugin-syntax-decorators', { legacy: true }],
// myPlugin should run here
['@babel/plugin-proposal-class-properties', { loose: true }]
]
},
})
Am I missing something or this is really not possible right now?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.