|
| 1 | +import { restoreJSX } from './restore-jsx' |
| 2 | +import * as babel from '@babel/core' |
| 3 | + |
| 4 | +async function jsx(sourceCode: string) { |
| 5 | + const [ast] = await restoreJSX(babel, sourceCode, 'test.js') |
| 6 | + if (ast === null) { |
| 7 | + return ast |
| 8 | + } |
| 9 | + const { code } = await babel.transformFromAstAsync(ast, null, { |
| 10 | + configFile: false |
| 11 | + }) |
| 12 | + return code |
| 13 | +} |
| 14 | +// jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; |
| 15 | +// React__default.createElement(Foo)`) |
| 16 | +// Tests adapted from: https://github.com/flying-sheep/babel-plugin-transform-react-createelement-to-jsx/blob/63137b6/test/index.js |
| 17 | +describe('restore-jsx', () => { |
| 18 | + it('should trans to ', async () => { |
| 19 | + expect( |
| 20 | + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; |
| 21 | + React__default.createElement(foo)`) |
| 22 | + ).toBeNull() |
| 23 | + expect( |
| 24 | + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; |
| 25 | + React__default.createElement("h1")`) |
| 26 | + ).toMatch(`<h1 />;`) |
| 27 | + expect( |
| 28 | + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; |
| 29 | + React__default.createElement(Foo)`) |
| 30 | + ).toMatch(`<Foo />;`) |
| 31 | + expect( |
| 32 | + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; |
| 33 | + React__default.createElement(Foo.Bar)`) |
| 34 | + ).toMatch(`<Foo.Bar />;`) |
| 35 | + expect( |
| 36 | + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; |
| 37 | + React__default.createElement(Foo.Bar.Baz)`) |
| 38 | + ).toMatch(`<Foo.Bar.Baz />;`) |
| 39 | + }) |
| 40 | + |
| 41 | + it('should handle props', async () => { |
| 42 | + expect( |
| 43 | + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; |
| 44 | + React__default.createElement(foo, {hi: there})`) |
| 45 | + ).toBeNull() |
| 46 | + expect( |
| 47 | + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; |
| 48 | + React__default.createElement("h1", {hi: there})`) |
| 49 | + ).toMatch(`<h1 hi={there} />;`) |
| 50 | + expect( |
| 51 | + await jsx(`import React__default, { PureComponent, Component, forwardRef, memo, createElement } from 'react'; |
| 52 | + React__default.createElement(Foo, {hi: there})`) |
| 53 | + ).toMatch(`<Foo hi={there} />;`) |
| 54 | + }) |
| 55 | +}) |
0 commit comments