Skip to content
This repository has been archived by the owner on Nov 21, 2024. It is now read-only.

Commit

Permalink
1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
Jarle Fagerheim committed Aug 18, 2016
0 parents commit 277aec7
Show file tree
Hide file tree
Showing 10 changed files with 345 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
presets: ["es2015"]
}
39 changes: 39 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules
jspm_packages

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

lib/
2 changes: 2 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*
!lib/*
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2016 Jarle Fagerheim

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# react-snapshot-test-generator
Automatically generate boilerplate for React component snapshot tests

## Rationale

[React Tree Snapshot Testing](https://facebook.github.io/jest/blog/2016/07/27/jest-14.html) is great, but defining the tests generates a fair bit of boilerplate. If your code structure follows some simple conventions, `react-snapshot-test-generator` can do the work for you.

## Getting started

### Requirements
If you're new to snapshot testing with [React](https://facebook.github.io/react) and [Jest](https://facebook.github.io/jest), check out the official tutorials ([React](https://facebook.github.io/jest/docs/tutorial-react.html), [React Native](https://facebook.github.io/jest/docs/tutorial-react-native.html)) and get your first test working before continuing.

The generator expects the component `<MyComponent />` to be available as the default export of a file named `MyComponent.js`. If your code has a different structure, you may want to modify the generator script accordingly.

### Installation
Once you have the test renderer working with Jest, run
```
npm install --save-dev react-snapshot-test-generator
```
in your project folder.

### Configuration
Before generating tests, you need to specify your components. Create a file named `snapshotTestConfig.js` in your project root folder that looks like this:

```javascript
module.exports = {
componentDefinitions: {
'components': [
'MySimpleConstantComponent', // Causes './components/MySimpleConstantComponent' to be imported
// and generates a snapshot test for <MySimpleConstantComponent />
],
'widgets': [
'MySimpleWidget', // Causes './widgets/MySimpleWidget' to be imported and generates a snapshot
// test for <MySimpleWidget />
['MyComplexWidget', [ // Props are specified as plain objects. The enclosing array is mandatory.
{aBooleanProp: false, aStringProp: "value"},
{aBooleanProp: true, aStringProp: "value"},
]], // Causes './widgets/MyComplexWidget' to be imported and generates snapshot tests for
// <MyComplexWidget aBooleanProp={false} aStringProp={"value"} /> as well as
// <MyComplexWidget aBooleanProp={true} aStringProp={"value"} />
],
},
autoMocks: ['TextInput'], // Optional: automatically generate simple mocks. Particularly useful
// for React Native.
}
```

In `package.json`, add scripts like the following for easy test generation:
```json
scripts: {
"generateTests": "react-snapshot-test-generator",
"test": "npm run generateTests && jest"
}
```

### Generating tests
Simply running `npm run generateTests` will read the configuration from `snapshotTestConfig.js` and generate a test file in `__tests__/snapshotTests.js`.

The test generation can be customized. Run `npm run generateTests -- -h` to get information about theavailable command line options. Note in particular the `-n` flag for generating React Native tests.

## License

[MIT](LICENSE)
27 changes: 27 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "react-snapshot-test-generator",
"version": "1.0.0",
"description": "Automatically generate boilerplate for React component snapshot tests",
"main": "lib/test-generator.js",
"scripts": {
"prepublish": "npm run build",
"build": "babel src -d lib",
"test": "babel tests.js | node"
},
"keywords": [
"testing",
"react",
"react-native"
],
"bin": {
"react-snapshot-test-generator": "lib/test-generator.js"
},
"author": "Jarle Fagerheim <jarle@fagerbua.no>",
"license": "MIT",
"devDependencies": {
"babel-cli": "^6.11.4",
"babel-preset-es2015": "^6.13.2",
"should": "^11.1.0",
"yargs": "^5.0.0"
}
}
21 changes: 21 additions & 0 deletions src/functions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { jestReactMock, jsxProp } from './templates'

export const parseDefinitions = (definitions) =>
Object.keys(definitions)
.map(path => ({path, components: definitions[path]}))
.map(({path, components}) => ({
path,
components: components.map(component => (
typeof(component) === 'string' ? {name: component, props: [{}] } :
{name: component[0], props: component[1]}
))}))

export const flatten = (nested, separator="\n") => nested.map(array => array.join(separator)).join(separator)
export const jestReactMocks = (mocks) => mocks.map(name => jestReactMock(name)).join("\n")
export const jsxProps = (props) => Object.keys(props)
.map(name => jsxProp(name, props[name]))
.join(" ")

export const transformDefinitions = (definitions, transformer) => flatten(parseDefinitions(definitions).map(transformer))

export default transformDefinitions
14 changes: 14 additions & 0 deletions src/templates.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export const componentImport = (path, name) => `import ${name} from '../${path}/${name}'`

export const jestReactMock = (mock) => `jest.mock('${mock}', () => '${mock}')`

export const jsxProp = (name, value) => `${name}={${value}}`

export const jsxTag = (name, props) => props.length > 0 ? `<${name} ${props} />` : `<${name} />`

export const testDescription = (componentName, componentProps) => `
describe('${jsxTag(componentName, componentProps)}', () => {
it('renders correctly', () => {
snapshotTest(${jsxTag(componentName, componentProps)})
})
})`
82 changes: 82 additions & 0 deletions src/test-generator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#!/usr/bin/env node

import yargs from 'yargs'
import fs from 'fs'
import transformDefinitions, { jestReactMocks, jsxProps } from './functions'
import { componentImport, testDescription } from './templates'

const argv = yargs.usage('Usage: $0 [options]')
.example('$0', 'Generates tests with default options')
.alias('d', 'output-directory')
.nargs('d', 1)
.describe('d', 'Output directory')
.default('d', '__tests__')
.alias('o', 'output')
.nargs('o', 1)
.default('o', 'snapshotTests')
.describe('o', 'Name of the output module')
.alias('c', 'config')
.nargs('c', 1)
.describe('c', 'Name of the config module')
.default('c', 'snapshotTestConfig')
.help('help')
.alias('h', 'help')
.alias('n', 'native')
.describe('n', 'Use React Native')
.default('n', false)
.alias('nm', 'native-module')
.describe('nm', 'Name of React Native module')
.nargs('nm', 1)
.default('nm', 'react-native')
.argv

const workingDirectory = process.cwd()
const configFilename = argv.config
const configFilepath = `${workingDirectory}/${configFilename}`

let configuration
try {
configuration = require(configFilepath)
} catch (error) {
console.error(error)
yargs.showHelp()
process.exit(1)
}

const { autoMocks, componentDefinitions } = configuration

const describedComponents = transformDefinitions(componentDefinitions,
({components}) => components.map(comp =>
comp.props.map(props => testDescription(comp.name, jsxProps(props)))
.join("\n")))

const componentImports = transformDefinitions(componentDefinitions,
({path, components}) => components.map(comp => componentImport(path, comp.name)))

const comment = `/* Component tests generated by react-snapshot-test-generator on ${new Date().toISOString()} */`

const reactNativeImport = argv.n ? `import '${argv.nm}'` : ""
const generatedMocks = autoMocks ? jestReactMocks(autoMocks) : ""

const template = `${comment}
${reactNativeImport}
import React from 'React'
import renderer from 'react-test-renderer'
function snapshotTest(element) {
const tree = renderer.create(element).toJSON()
expect(tree).toMatchSnapshot()
}
${generatedMocks}
${componentImports}
${describedComponents}
`

const outputFile = argv.output
const outputDir = argv['output-directory']

if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir)
fs.writeFile(`${workingDirectory}/${outputDir}/${outputFile}.js`, template)
73 changes: 73 additions & 0 deletions tests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import 'should'
import * as f from "./lib/functions"
import * as t from "./lib/templates"

console.log('Running tests ...')
f.parseDefinitions({
'path/to/somewhere': [
['FirstComponent', [{prop1: "value1", prop2: "value2"},
{prop3: "value3", prop4: "value4"}],
]],
'path/to/elsewhere': [
'ThirdComponent',
['FourthComponent', [{prop7: "value7", prop8: "value8"}]],
],
}).should.deepEqual([
{ path: 'path/to/somewhere',
components: [
{
name: 'FirstComponent',
props: [
{prop1: "value1", prop2: "value2"},
{prop3: "value3", prop4: "value4"},
],
},
],
},
{ path: 'path/to/elsewhere',
components: [
{
name: 'ThirdComponent',
props: [{}],
},
{
name: 'FourthComponent',
props: [{prop7: "value7", prop8: "value8"}],
},
],
},
])

f.flatten([["this", "that"], ["something", "else"]]).should.equal("this\nthat\nsomething\nelse")

t.jestReactMock("Module").should.equal("jest.mock('Module', () => 'Module')")

f.jestReactMocks(["Module1", "Module2"]).should.equal("jest.mock('Module1', () => 'Module1')\njest.mock('Module2', () => 'Module2')")

t.componentImport('here/there', 'TestComponent').should.equal("import TestComponent from '../here/there/TestComponent'")

t.jsxProp('key', 'value').should.equal("key={value}")

f.jsxProps({key1: 'value1', key2: 'value2'}).should.equal("key1={value1} key2={value2}")

f.jsxProps({}).should.equal("")

t.jsxTag("Test", "key={val}").should.equal('<Test key={val} />')

t.jsxTag("Test", "").should.equal('<Test />')

t.testDescription("TestComponent", "key={value} key2={anotherValue}").should.equal(`
describe('<TestComponent key={value} key2={anotherValue} />', () => {
it('renders correctly', () => {
snapshotTest(<TestComponent key={value} key2={anotherValue} />)
})
})`)

t.testDescription("TestComponent", "").should.equal(`
describe('<TestComponent />', () => {
it('renders correctly', () => {
snapshotTest(<TestComponent />)
})
})`)

console.log("All tests passed!")

0 comments on commit 277aec7

Please sign in to comment.