Skip to content

Commit

Permalink
Add tests for CLI generators (#401)
Browse files Browse the repository at this point in the history
* Remove global mocks, localize to test.

* Remove more global mocks.

* Make dbCommand tests work again.

* Write snapshot tests for generators.

* Add generate tests and snaps.

* Play around with snapshot testing.

* Update snapshots.

* Complete reorg of generator files and templates, adds text and fixture directories

Cell test working

* Component, layout, page and service tests

* Adds tests for generator helpers.js

* More tests

* Comment out some variables that aren't being used for now

* Adds multi-word cell tests

* Variable name change

* Adds multi-word component tests

* Component test fix

* Adds multi-word layout tests

* Adds multi-word page tests

* Creates multi-word and CRUD sdl tests

* Adds multi word tests for service

* Adds scaffold tests

* Count actual number of files returned

* Rename test directories to __tests__

* Adds tests for src/lib/index

* Ignore any files named "test" inside a fixtures directory

* Adds generateTemplate tests

* Ignore fixture files when linting

* fix babel build ignore error using rimraf (rm -rf)

Babel flag --no-copy-ignored has a bug and does not respect our ignored config. For a short term fix, I'm using rimraf package (cross-platform support) to clean up __tests__ folders that shouldn't be in dist/

* Converts SDL generator to use same sub-generator technique as scaffold generator

* Updates README with new generator file structure

* Removes .fixture extensions

* Remove unused argument

Co-authored-by: Rob Cameron <rob.cameron@fastmail.com>
Co-authored-by: David S Price <thedavid@thedavidprice.com>
  • Loading branch information
3 people authored Apr 10, 2020
1 parent 05bfc65 commit 8d510db
Show file tree
Hide file tree
Showing 101 changed files with 2,329 additions and 119 deletions.
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@
"typescript": "^3.8.3"
},
"eslintConfig": {
"extends": "@redwoodjs/eslint-config"
"extends": "@redwoodjs/eslint-config",
"ignorePatterns": [
"fixtures"
]
},
"eslintIgnore": [
"dist",
Expand Down
15 changes: 0 additions & 15 deletions packages/cli/__mocks__/@redwoodjs/internal.js

This file was deleted.

5 changes: 0 additions & 5 deletions packages/cli/__mocks__/fs.js

This file was deleted.

1 change: 1 addition & 0 deletions packages/cli/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
module.exports = {
testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/*.test.[jt]s?(x)'],
testPathIgnorePatterns: ['fixtures'],
}
5 changes: 4 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,16 @@
"pascalcase": "^1.0.0",
"pluralize": "^8.0.0",
"prettier": "^2.0.2",
"rimraf": "^3.0.2",
"yargs": "^15.3.1"
},
"devDependencies": {
"@types/node-fetch": "^2.5.5"
},
"scripts": {
"build": "yarn cross-env NODE_ENV=production babel src -d dist --delete-dir-on-start --copy-files --no-copy-ignored",
"build": "yarn build:all && yarn build:clean",
"build:all": "yarn cross-env NODE_ENV=production yarn babel src -d dist --delete-dir-on-start --copy-files --no-copy-ignored",
"build:clean": "yarn rimraf 'dist/**/__tests__'",
"build:watch": "nodemon --ignore dist --exec 'yarn build'",
"test": "jest",
"test:watch": "yarn test --watch"
Expand Down
20 changes: 17 additions & 3 deletions packages/cli/src/commands/dbCommands/__tests__/dbCommands.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
jest.mock('@redwoodjs/internal')
jest.mock('src/lib')

import { runCommandTask } from 'src/lib'

import * as up from '../up'
Expand All @@ -9,7 +6,24 @@ import * as save from '../save'
import * as generate from '../generate'
import * as seed from '../seed'

jest.mock('src/lib', () => {
return {
...require.requireActual('src/lib'),
runCommandTask: jest.fn((commands) => {
return commands.map(({ cmd, args }) => `${cmd} ${args.join(' ')}`)
}),
getPaths: () => ({
api: {},
web: {},
}),
}
})

describe('db commands', () => {
afterAll(() => {
jest.clearAllMocks()
})

it('some commands have a verbose flag', () => {
expect(up.builder.verbose).toBeDefined()
expect(down.builder.verbose).toBeDefined()
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ export const aliases = ['g']
export const desc = 'Save time by generating boilerplate code.'

export const builder = (yargs) =>
yargs.commandDir('./generate/commands').demandCommand().argv
yargs.commandDir('./generate', { recurse: true }).demandCommand().argv
24 changes: 7 additions & 17 deletions packages/cli/src/commands/generate/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

## Creating a Generator

Generators go in `src/commands/generate/commands` and should be named for the generate command that invokes them (not required). For example, for page generator invoked with:
Generators go in `src/commands/generate` and should be named for the generate command that invokes them (not required). For example, for page generator invoked with:

redwood generate page foo

you would create `src/commands/generate/commands/page.js`. The file name does not have to match the generator command (the name is pulled from the object returned when importing the generator) but it is clearest to have the command and the name match.
you would create `src/commands/generate/page/page.js`. The file name does not have to match the generator command (the name is pulled from the object returned when importing the generator) but it is clearest to have the command and the name match.

The generator must export the following:

Expand All @@ -19,21 +19,11 @@ A typicall generator writes files.

## Templates

Templates for the files created by generators go in `src/commands/generate/templates` and should be named after the command that invokes your generator. The files inside should end in `.template` to avoid being compiled by Babel.
Templates for the files created by generators go in `src/commands/generate/[name]/templates` and should be named after the command that invokes your generator. The files inside should end in `.template` to avoid being compiled by Babel.

src/commands/generate/
├── generators
│ ├── component.js
│ └── page.js
└── templates
├── component
│ ├── component.js.template
│ ├── readme.mdx.template
└── page
├── templates
│ ├── page.js.template
│ └── test.js.template
└── page
└── page.js.template

## TODO

- Check for existence of route before writing, console output skipping if already exists
- Remove `import` statements from service files once photon is automatically included
└── page.js
119 changes: 119 additions & 0 deletions packages/cli/src/commands/generate/__tests__/helpers.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
global.__dirname = __dirname
import {} from 'src/lib/test'

import * as helpers from '../helpers'

const PAGE_TEMPLATE_OUTPUT = `const FooBarPage = () => {
return (
<div>
<h1>FooBarPage</h1>
<p>Find me in ./web/src/pages/FooBarPage/FooBarPage.js</p>
</div>
)
}
export default FooBarPage
`

test('templateForComponentFile creates a proper output path for files', () => {
const names = ['FooBar', 'fooBar', 'foo-bar', 'foo_bar', 'FOO_BAR']

names.forEach((name) => {
const output = helpers.templateForComponentFile({
name: name,
suffix: 'Page',
webPathSection: 'pages',
generator: 'page',
templatePath: 'page.js.template',
})

expect(output[0]).toEqual(
'/path/to/project/web/src/pages/FooBarPage/FooBarPage.js'
)
})
})

test('templateForComponentFile can create a path in /web', () => {
const output = helpers.templateForComponentFile({
name: 'Home',
suffix: 'Page',
webPathSection: 'pages',
generator: 'page',
templatePath: 'page.js.template',
})

expect(output[0]).toEqual(
'/path/to/project/web/src/pages/HomePage/HomePage.js'
)
})

test('templateForComponentFile can create a path in /api', () => {
const output = helpers.templateForComponentFile({
name: 'Home',
suffix: 'Page',
apiPathSection: 'services',
generator: 'page',
templatePath: 'page.js.template',
})

expect(output[0]).toEqual(
'/path/to/project/api/src/services/HomePage/HomePage.js'
)
})

test('templateForComponentFile can override generated component name', () => {
const output = helpers.templateForComponentFile({
name: 'Home',
componentName: 'Hobbiton',
webPathSection: 'pages',
generator: 'page',
templatePath: 'page.js.template',
})

expect(output[0]).toEqual(
'/path/to/project/web/src/pages/Hobbiton/Hobbiton.js'
)
})

test('templateForComponentFile can override file extension', () => {
const output = helpers.templateForComponentFile({
name: 'Home',
suffix: 'Page',
extension: '.txt',
webPathSection: 'pages',
generator: 'page',
templatePath: 'page.js.template',
})

expect(output[0]).toEqual(
'/path/to/project/web/src/pages/HomePage/HomePage.txt'
)
})

test('templateForComponentFile creates a template', () => {
const output = helpers.templateForComponentFile({
name: 'FooBar',
suffix: 'Page',
webPathSection: 'pages',
generator: 'page',
templatePath: 'page.js.template',
})

expect(output[1]).toEqual(PAGE_TEMPLATE_OUTPUT)
})

test('pathName uses passed path if present', () => {
const paths = ['FooBar', 'fooBar', 'foo-bar', 'foo_bar', 'foobar', '/foobar']

paths.forEach((path) => {
expect(helpers.pathName(path, 'FooBar')).toEqual(path)
})
})

test('pathName creates path based on name if path is null', () => {
const names = ['FooBar', 'fooBar', 'foo-bar', 'foo_bar', 'FOO_BAR']

names.forEach((name) => {
expect(helpers.pathName(null, name)).toEqual('/foo-bar')
})
})
45 changes: 45 additions & 0 deletions packages/cli/src/commands/generate/cell/__tests__/cell.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
global.__dirname = __dirname
import { loadGeneratorFixture } from 'src/lib/test'

import * as cell from '../cell'

let singleWordFiles, multiWordFiles

beforeAll(() => {
singleWordFiles = cell.files({ name: 'User' })
multiWordFiles = cell.files({ name: 'UserProfile' })
})

test('returns exactly 2 files', () => {
expect(Object.keys(singleWordFiles).length).toEqual(2)
})

test('creates a cell component with a single word name', () => {
expect(
singleWordFiles['/path/to/project/web/src/components/UserCell/UserCell.js']
).toEqual(loadGeneratorFixture('cell', 'singleWordCell.js'))
})

test('creates a cell test with a single word name', () => {
expect(
singleWordFiles[
'/path/to/project/web/src/components/UserCell/UserCell.test.js'
]
).toEqual(loadGeneratorFixture('cell', 'singleWordCell.test.js'))
})

test('creates a cell component with a multi word name', () => {
expect(
multiWordFiles[
'/path/to/project/web/src/components/UserProfileCell/UserProfileCell.js'
]
).toEqual(loadGeneratorFixture('cell', 'multiWordCell.js'))
})

test('creates a cell test with a multi word name', () => {
expect(
multiWordFiles[
'/path/to/project/web/src/components/UserProfileCell/UserProfileCell.test.js'
]
).toEqual(loadGeneratorFixture('cell', 'multiWordCell.test.js'))
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const QUERY = gql`
query {
userProfile {
id
}
}
`

export const Loading = () => <div>Loading...</div>

export const Empty = () => <div>Empty</div>

export const Failure = ({ error }) => <div>Error: {error.message}</div>

export const Success = ({ userProfile }) => {
return JSON.stringify(userProfile)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { render, cleanup, screen } from '@testing-library/react'

import { Loading, Empty, Failure, Success } from './UserProfileCell'

describe('UserProfileCell', () => {
afterEach(() => {
cleanup()
})

it('Loading renders successfully', () => {
render(<Loading />)
// Use screen.debug() to see output.
expect(screen.queryByText('Loading...')).toBeInTheDocument()
})

it('Empty renders successfully', () => {
render(<Empty />)
expect(screen.queryByText('Empty')).toBeInTheDocument()
})

it('Failure renders successfully', () => {
render(<Failure error={{ message: 'Oh no!' }} />)
expect(screen.queryByText('Error: Oh no!')).toBeInTheDocument()
})

it('Success renders successfully', () => {
render(
<Success userExample={{ userProfile: { objectKey: 'objectValue' } }} />
)
expect(
screen.queryByText('{"userProfile":{"objectKey":"objectValue"}}')
).toBeInTheDocument()
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const QUERY = gql`
query {
user {
id
}
}
`

export const Loading = () => <div>Loading...</div>

export const Empty = () => <div>Empty</div>

export const Failure = ({ error }) => <div>Error: {error.message}</div>

export const Success = ({ user }) => {
return JSON.stringify(user)
}
Loading

0 comments on commit 8d510db

Please sign in to comment.