Last active
June 18, 2019 12:17
-
-
Save rastating/719f7f7b9f88100270f455f78c15c0d0 to your computer and use it in GitHub Desktop.
A script to create the boilerplate code for a new React.js component with a [Jest] spec file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env node | |
# Usage: node create-react-component.js ComponentName | |
# Note: If a `components` directory does not exist in the current working directory, nothing will be created | |
const fs = require('fs') | |
const path = require('path') | |
const componentName = process.argv[2] | |
const componentPath = path.join( | |
'components', | |
componentName | |
) | |
let rollUpContent = ` | |
import ${componentName} from './${componentName}' | |
export default ${componentName} | |
`.trimLeft() | |
let rollUpSpec = ` | |
import DefaultExport from './index' | |
import ${componentName} from './${componentName}' | |
describe('${componentName} rollup', () => { | |
it('should export ${componentName} as the default class', () => { | |
expect(DefaultExport).toBe(${componentName}) | |
}) | |
}) | |
`.trimLeft() | |
let componentContent = ` | |
import React from 'react' | |
class ${componentName} extends React.Component { | |
render () { | |
return ( | |
<div /> | |
) | |
} | |
} | |
export default ${componentName} | |
`.trimLeft() | |
let componentSpec = ` | |
import React from 'react' | |
import { shallow } from 'enzyme' | |
import ${componentName} from './index' | |
describe('<${componentName} />', () => { | |
it('should not render children', () => { | |
const wrapper = shallow( | |
<${componentName}> | |
<div className="unique" /> | |
</${componentName}> | |
) | |
expect(wrapper.find('div.unique')).toHaveLength(0) | |
}) | |
}) | |
`.trimLeft() | |
fs.mkdir(componentPath, (error) => { | |
if (error) { | |
return console.log('Could not create the directory') | |
} | |
fs.writeFile(path.join(componentPath, 'index.jsx'), rollUpContent, (error) => { | |
if (error) { | |
console.log('Failed to create the rollup') | |
} | |
}) | |
fs.writeFile(path.join(componentPath, 'index.spec.jsx'), rollUpSpec, (error) => { | |
if (error) { | |
console.log('Failed to create the rollup spec') | |
} | |
}) | |
fs.writeFile(path.join(componentPath, `${componentName}.jsx`), componentContent, (error) => { | |
if (error) { | |
console.log('Failed to create the component') | |
} | |
}) | |
fs.writeFile(path.join(componentPath, `${componentName}.spec.jsx`), componentSpec, (error) => { | |
if (error) { | |
console.log('Failed to create the component spec') | |
} | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment