Browse Source

update tailwind and dep tests

pull/58/head
Nicolas Beaussart 6 years ago
parent
commit
fdca074973
  1. 17
      src/tests/add/__snapshots__/dep.spec.ts.snap
  2. 60
      src/tests/add/__snapshots__/tailwind.spec.ts.snap
  3. 26
      src/tests/add/dep.spec.ts
  4. 410
      src/tests/add/tailwind.spec.ts
  5. 79
      src/tests/test-helpers.spec.ts

17
src/tests/add/__snapshots__/dep.spec.ts.snap

@ -1,12 +1,17 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`dep should fail if dependancy is already in package.json 1`] = `[Error: Config not found. Tried to look for a .nbxrc, .nbxrc.json, .nbxrc.yaml, .nbxrc.yml, .nbxrc.js]`;
exports[`nbx add:dep should fail if dependancy is already in package.json 1`] = `
Array [
"Adding chalk as a dependency",
"The step was done without any error.",
]
`;
exports[`dep should fail if dev dependancy is already in package.json 1`] = `[Error: chalk is already installed in this project.]`;
exports[`nbx add:dep should fail if dev dependancy is already in package.json 1`] = `Array []`;
exports[`dep should fail if no package.json found 1`] = `[Error: There is no package.json not found in the current folder]`;
exports[`nbx add:dep should fail if no package.json found 1`] = `Array []`;
exports[`dep should print help correctly 1`] = `
exports[`nbx add:dep should print help correctly 1`] = `
Array [ Array [
"proxy to yarn add, plus gitmoji commit "proxy to yarn add, plus gitmoji commit
", ",
@ -30,14 +35,14 @@ EXAMPLES
] ]
`; `;
exports[`dep should work with a dev dependency 1`] = `
exports[`nbx add:dep should work with a dev dependency 1`] = `
Array [ Array [
"Adding chalk as a dev dependency", "Adding chalk as a dev dependency",
"The step was done without any error.", "The step was done without any error.",
] ]
`; `;
exports[`dep should work with dependency 1`] = `
exports[`nbx add:dep should work with dependency 1`] = `
Array [ Array [
"Adding chalk as a dependency", "Adding chalk as a dependency",
"The step was done without any error.", "The step was done without any error.",

60
src/tests/add/__snapshots__/tailwind.spec.ts.snap

@ -1,6 +1,10 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`tailwind should print help correctly 1`] = `
exports[`nbx add:tailwind should error if no react is found 1`] = `Array []`;
exports[`nbx add:tailwind should fail if no package.json found 1`] = `Array []`;
exports[`nbx add:tailwind should print help correctly 1`] = `
Array [ Array [
"add tailwindcss to a project "add tailwindcss to a project
", ",
@ -15,7 +19,7 @@ OPTIONS
] ]
`; `;
exports[`tailwind should work on a react application with commits 1`] = `
exports[`nbx add:tailwind should work on a react application with commits 1`] = `
"const purgecss = require('@fullhuman/postcss-purgecss')({ "const purgecss = require('@fullhuman/postcss-purgecss')({
content: ['./src/**/*.jsx', './src/**/*.js', './src/index.js', './public/index.html'], content: ['./src/**/*.jsx', './src/**/*.js', './src/index.js', './public/index.html'],
css: ['./src/tailwind.css'], css: ['./src/tailwind.css'],
@ -32,7 +36,32 @@ module.exports = {
" "
`; `;
exports[`tailwind should work on a react application without commits 1`] = `
exports[`nbx add:tailwind should work on a react application with commits 2`] = `
Array [
"Adding @fullhuman/postcss-purgecss as a dev dependency",
"The step was done without any error.",
"Adding autoprefixer as a dev dependency",
"The step was done without any error.",
"Adding npm-run-all as a dev dependency",
"The step was done without any error.",
"Adding postcss-cli as a dev dependency",
"The step was done without any error.",
"Adding tailwindcss as a dependency",
"The step was done without any error.",
"Generating tailwind initial config",
"The step was done without any error.",
"Generating postcss",
"The step was done without any error.",
"Generating tailwind full css",
"The step was done without any error.",
"Adding package.json scripts",
"The step was done without any error.",
"Adding full tailwind css to .gitignore",
"The step was done without any error.",
]
`;
exports[`nbx add:tailwind should work on a react application without commits 1`] = `
"const purgecss = require('@fullhuman/postcss-purgecss')({ "const purgecss = require('@fullhuman/postcss-purgecss')({
content: ['./src/**/*.jsx', './src/**/*.js', './src/index.js', './public/index.html'], content: ['./src/**/*.jsx', './src/**/*.js', './src/index.js', './public/index.html'],
css: ['./src/tailwind.css'], css: ['./src/tailwind.css'],
@ -48,3 +77,28 @@ module.exports = {
}; };
" "
`; `;
exports[`nbx add:tailwind should work on a react application without commits 2`] = `
Array [
"Adding @fullhuman/postcss-purgecss as a dev dependency",
"The step was done without any error.",
"Adding autoprefixer as a dev dependency",
"The step was done without any error.",
"Adding npm-run-all as a dev dependency",
"The step was done without any error.",
"Adding postcss-cli as a dev dependency",
"The step was done without any error.",
"Adding tailwindcss as a dependency",
"The step was done without any error.",
"Generating tailwind initial config",
"The step was done without any error.",
"Generating postcss",
"The step was done without any error.",
"Generating tailwind full css",
"The step was done without any error.",
"Adding package.json scripts",
"The step was done without any error.",
"Adding full tailwind css to .gitignore",
"The step was done without any error.",
]
`;

26
src/tests/add/dep.spec.ts

@ -1,12 +1,7 @@
import { filesystem } from 'gluegun'; import { filesystem } from 'gluegun';
import * as latestVersion from 'latest-version'; import * as latestVersion from 'latest-version';
import Dep from '../../commands/add/dep'; import Dep from '../../commands/add/dep';
import {
createDefaultNbxConfig,
expectFailCli,
expectGitCommits,
testCli,
} from '../test-helpers.spec';
import { expectFailCli, expectGitCommits, testCli } from '../test-helpers.spec';
jest.setTimeout(90000); jest.setTimeout(90000);
@ -25,26 +20,25 @@ testCli({
}, },
}), }),
}, },
/*
*/
{ {
name: 'fail if dependancy is already in package.json', name: 'fail if dependancy is already in package.json',
runner: expectFailCli({ runner: expectFailCli({
args: ['chalk'], args: ['chalk'],
errorMessage: 'chalk is already installed in this project',
before: async () => {
await createDefaultNbxConfig();
filesystem.write('package.json', { dependencies: { chalk: '2.3.2' } });
},
errorMessage: 'chalk is already installed in this project.',
packageJson: { dependencies: { chalk: '2.3.2' } },
withGitSetup: true,
}), }),
}, },
{ {
name: 'fail if dev dependancy is already in package.json', name: 'fail if dev dependancy is already in package.json',
runner: expectFailCli({ runner: expectFailCli({
args: ['chalk', '-D'], args: ['chalk', '-D'],
errorMessage: 'chalk is already installed in this project',
before: async () => {
await createDefaultNbxConfig();
filesystem.write('package.json', { devDependencies: { chalk: '2.3.2' } });
},
errorMessage: 'chalk is already installed in this project.',
packageJson: { devDependencies: { chalk: '2.3.2' } },
withGitSetup: true,
}), }),
}, },
{ {

410
src/tests/add/tailwind.spec.ts

@ -1,271 +1,157 @@
import { filesystem, system } from 'gluegun';
const stripANSI = require('strip-ansi');
import { filesystem } from 'gluegun';
import * as prompts from 'prompts'; import * as prompts from 'prompts';
import * as latestVersion from 'latest-version'; import * as latestVersion from 'latest-version';
import Tailwind from '../../commands/add/tailwind'; import Tailwind from '../../commands/add/tailwind';
import {
expectFailCli,
expectFailGitCommits,
expectGitCommits,
testCli,
} from '../test-helpers.spec';
jest.setTimeout(90000); jest.setTimeout(90000);
/* eslint-disable no-console,max-nested-callbacks,@typescript-eslint/ban-ts-ignore */
let consoleLogOutput: string[];
let execPath: string;
const originalCwd = process.cwd();
const originalLog = console.log;
beforeEach(async () => {
consoleLogOutput = [];
console.log = (x: any) => consoleLogOutput.push(stripANSI(x));
const tmpDirName = `${new Date().getTime()}-${Math.random() * 100}-add-nbx-test`;
execPath = filesystem.path('/', 'tmp', tmpDirName);
filesystem.dir(execPath);
process.chdir(execPath);
});
afterEach(() => {
console.log = originalLog;
process.chdir(originalCwd);
jest.restoreAllMocks();
filesystem.remove(execPath);
});
const initWithConfigAndCommit = async (packageJson = {}) => {
await system.run('git init');
filesystem.write('.nbxrc', { git: { user: 'aaa', email: 'bbb' } });
filesystem.write('package.json', packageJson);
filesystem.write('test.html', '<html><body><a>testokiii</a></body></html>');
await system.run('touch yarn.lock');
await system.run('echo node_modules > .gitignore');
await system.run('git add * .nbxrc .gitignore');
try {
await system.run('git config user.email "you@example.com"');
await system.run('git config user.name "Your Name"');
} catch {}
await system.run('git commit -m "init state"');
};
describe('tailwind', () => {
it('should print help correctly', async () => {
try {
await Tailwind.run(['-h']);
} catch {}
expect(consoleLogOutput).toMatchSnapshot();
});
it('should error if no react is found', async () => {
await initWithConfigAndCommit();
try {
await Tailwind.run(['--no-spinner']);
// eslint-disable-next-line unicorn/catch-error-name
} catch (e) {
expect(e).toEqual(new Error('This script support only for now create react apps.'));
}
const after = await system.run('git log --name-status --format="%s"');
const afterSlitted = after
.split('\n')
.map(val => val.trim())
.map(val => stripANSI(val))
.filter(val => val !== '');
expect(afterSlitted).toHaveLength(6);
});
it('should work on a react application without commits', async () => {
await initWithConfigAndCommit({
name: 'sample',
version: '0.1.0',
private: true,
dependencies: {
'react-scripts': '3.3.1',
},
scripts: {
start: 'react-scripts start',
build: 'react-scripts build',
test: 'react-scripts test',
eject: 'react-scripts eject',
},
eslintConfig: {
extends: 'react-app',
},
browserslist: {
production: ['>0.2%', 'not dead', 'not op_mini all'],
development: ['last 1 chrome version', 'last 1 firefox version', 'last 1 safari version'],
},
});
prompts.inject([false]);
const [tailwind, purgecss, autoprefixer, npmRunAll, postcss] = await Promise.all([
latestVersion('tailwindcss'),
latestVersion('@fullhuman/postcss-purgecss'),
latestVersion('autoprefixer'),
latestVersion('npm-run-all'),
latestVersion('postcss-cli'),
]);
await Tailwind.run(['--no-spinner']);
const status = await system.run('git status --short');
const packageJson = filesystem.read('package.json', 'json');
const after = await system.run('git log --name-status --format="%s"');
const afterSlitted = after
.split('\n')
.map(val => val.trim())
.map(val => stripANSI(val))
.filter(val => val !== '');
expect(afterSlitted).toHaveLength(6);
expect(status.split('\n')).toStrictEqual([
' M .gitignore',
' M package.json',
' M yarn.lock',
'?? postcss.config.js',
'?? src/',
'?? tailwind.config.js',
'',
]);
expect(filesystem.read('postcss.config.js', 'utf8')).toMatchSnapshot();
expect(packageJson).toStrictEqual({
name: 'sample',
version: '0.1.0',
private: true,
dependencies: {
'react-scripts': '3.3.1',
'tailwindcss': tailwind,
},
devDependencies: {
'@fullhuman/postcss-purgecss': purgecss,
'autoprefixer': autoprefixer,
'npm-run-all': npmRunAll,
'postcss-cli': postcss,
},
scripts: {
'start': 'npm-run-all -p start:css start:js',
'start:css': 'postcss src/css/tailwind.src.css -o src/tailwind.css -w',
'start:js': 'react-scripts start',
'build': 'npm-run-all build:css build:js',
'build:css': 'postcss src/css/tailwind.src.css -o src/tailwind.css --env production',
'build:js': 'react-scripts build',
'test': 'react-scripts test',
'eject': 'react-scripts eject',
},
eslintConfig: {
extends: 'react-app',
},
browserslist: {
production: ['>0.2%', 'not dead', 'not op_mini all'],
development: ['last 1 chrome version', 'last 1 firefox version', 'last 1 safari version'],
},
});
const checkPackgeAndPostcssConfig = async () => {
const [tailwind, purgecss, autoprefixer, npmRunAll, postcss] = await Promise.all([
latestVersion('tailwindcss'),
latestVersion('@fullhuman/postcss-purgecss'),
latestVersion('autoprefixer'),
latestVersion('npm-run-all'),
latestVersion('postcss-cli'),
]);
const packageJson = filesystem.read('package.json', 'json');
expect(filesystem.read('postcss.config.js', 'utf8')).toMatchSnapshot();
expect(packageJson).toStrictEqual({
name: 'sample',
version: '0.1.0',
private: true,
dependencies: {
'react-scripts': '3.3.1',
'tailwindcss': tailwind,
},
devDependencies: {
'@fullhuman/postcss-purgecss': purgecss,
'autoprefixer': autoprefixer,
'npm-run-all': npmRunAll,
'postcss-cli': postcss,
},
scripts: {
'start': 'npm-run-all -p start:css start:js',
'start:css': 'postcss src/css/tailwind.src.css -o src/tailwind.css -w',
'start:js': 'react-scripts start',
'build': 'npm-run-all build:css build:js',
'build:css': 'postcss src/css/tailwind.src.css -o src/tailwind.css --env production',
'build:js': 'react-scripts build',
'test': 'react-scripts test',
'eject': 'react-scripts eject',
},
}); });
};
it('should work on a react application with commits', async () => {
await initWithConfigAndCommit({
name: 'sample',
version: '0.1.0',
private: true,
dependencies: {
'react-scripts': '3.3.1',
},
scripts: {
start: 'react-scripts start',
build: 'react-scripts build',
test: 'react-scripts test',
eject: 'react-scripts eject',
},
eslintConfig: {
extends: 'react-app',
},
browserslist: {
production: ['>0.2%', 'not dead', 'not op_mini all'],
development: ['last 1 chrome version', 'last 1 firefox version', 'last 1 safari version'],
},
});
prompts.inject([true]);
const [tailwind, purgecss, autoprefixer, npmRunAll, postcss] = await Promise.all([
latestVersion('tailwindcss'),
latestVersion('@fullhuman/postcss-purgecss'),
latestVersion('autoprefixer'),
latestVersion('npm-run-all'),
latestVersion('postcss-cli'),
]);
await Tailwind.run(['--no-spinner']);
const packageJson = filesystem.read('package.json', 'json');
const after = await system.run('git log --name-status --format="%s"');
const afterSlitted = after
.split('\n')
.map(val => val.trim())
.map(val => stripANSI(val))
.filter(val => val !== '');
expect(afterSlitted).toStrictEqual([
':see_no_evil: add generated tailwind to .gitignore',
'M\t.gitignore',
':wrench: add script for tailwind to package.json',
'M\tpackage.json',
':wrench: add tailwind css file',
'A\tsrc/css/tailwind.src.css',
':wrench: add postcss config file',
'A\tpostcss.config.js',
':wrench: add tailwind config file',
'A\ttailwind.config.js',
`:heavy_plus_sign: add tailwindcss@${tailwind} as a dependency`,
'M\tpackage.json',
'M\tyarn.lock',
`:heavy_plus_sign: add postcss-cli@${postcss} as a dev dependency`,
'M\tpackage.json',
'M\tyarn.lock',
`:heavy_plus_sign: add npm-run-all@${npmRunAll} as a dev dependency`,
'M\tpackage.json',
'M\tyarn.lock',
`:heavy_plus_sign: add autoprefixer@${autoprefixer} as a dev dependency`,
'M\tpackage.json',
'M\tyarn.lock',
`:heavy_plus_sign: add @fullhuman/postcss-purgecss@${purgecss} as a dev dependency`,
'M\tpackage.json',
'M\tyarn.lock',
'init state',
'A\t.gitignore',
'A\t.nbxrc',
'A\tpackage.json',
'A\ttest.html',
'A\tyarn.lock',
]);
expect(filesystem.read('postcss.config.js', 'utf8')).toMatchSnapshot();
expect(packageJson).toStrictEqual({
name: 'sample',
version: '0.1.0',
private: true,
dependencies: {
'react-scripts': '3.3.1',
'tailwindcss': tailwind,
},
devDependencies: {
'@fullhuman/postcss-purgecss': purgecss,
'autoprefixer': autoprefixer,
'npm-run-all': npmRunAll,
'postcss-cli': postcss,
},
scripts: {
'start': 'npm-run-all -p start:css start:js',
'start:css': 'postcss src/css/tailwind.src.css -o src/tailwind.css -w',
'start:js': 'react-scripts start',
'build': 'npm-run-all build:css build:js',
'build:css': 'postcss src/css/tailwind.src.css -o src/tailwind.css --env production',
'build:js': 'react-scripts build',
'test': 'react-scripts test',
'eject': 'react-scripts eject',
},
eslintConfig: {
extends: 'react-app',
},
browserslist: {
production: ['>0.2%', 'not dead', 'not op_mini all'],
development: ['last 1 chrome version', 'last 1 firefox version', 'last 1 safari version'],
},
});
});
testCli({
runCommand: (args: string[]) => Tailwind.run(args),
name: 'nbx add:tailwind',
defaultArgs: ['--no-spinner'],
tests: [
{
name: 'fail if no package.json found',
runner: expectFailCli({
errorMessage: 'There is no package.json not found in the current folder',
before: async () => {
filesystem.remove('package.json');
},
}),
},
{
name: 'error if no react is found',
runner: expectFailGitCommits({
errorMessage: 'This script support only for now create react apps.',
}),
},
{
name: 'work on a react application without commits',
runner: expectGitCommits({
packageJson: {
name: 'sample',
version: '0.1.0',
private: true,
dependencies: {
'react-scripts': '3.3.1',
},
scripts: {
start: 'react-scripts start',
build: 'react-scripts build',
test: 'react-scripts test',
eject: 'react-scripts eject',
},
},
expectGitLog: [],
before: async () => {
prompts.inject([false]);
},
checks: checkPackgeAndPostcssConfig,
}),
},
{
name: 'work on a react application with commits',
runner: expectGitCommits({
packageJson: {
name: 'sample',
version: '0.1.0',
private: true,
dependencies: {
'react-scripts': '3.3.1',
},
scripts: {
start: 'react-scripts start',
build: 'react-scripts build',
test: 'react-scripts test',
eject: 'react-scripts eject',
},
},
expectGitLog: async () => {
const [tailwind, purgecss, autoprefixer, npmRunAll, postcss] = await Promise.all([
latestVersion('tailwindcss'),
latestVersion('@fullhuman/postcss-purgecss'),
latestVersion('autoprefixer'),
latestVersion('npm-run-all'),
latestVersion('postcss-cli'),
]);
return [
':see_no_evil: add generated tailwind to .gitignore',
'M\t.gitignore',
':wrench: add script for tailwind to package.json',
'M\tpackage.json',
':wrench: add tailwind css file',
'A\tsrc/css/tailwind.src.css',
':wrench: add postcss config file',
'A\tpostcss.config.js',
':wrench: add tailwind config file',
'A\ttailwind.config.js',
`:heavy_plus_sign: add tailwindcss@${tailwind} as a dependency`,
'M\tpackage.json',
'M\tyarn.lock',
`:heavy_plus_sign: add postcss-cli@${postcss} as a dev dependency`,
'M\tpackage.json',
'M\tyarn.lock',
`:heavy_plus_sign: add npm-run-all@${npmRunAll} as a dev dependency`,
'M\tpackage.json',
'M\tyarn.lock',
`:heavy_plus_sign: add autoprefixer@${autoprefixer} as a dev dependency`,
'M\tpackage.json',
'M\tyarn.lock',
`:heavy_plus_sign: add @fullhuman/postcss-purgecss@${purgecss} as a dev dependency`,
'M\tpackage.json',
'M\tyarn.lock',
];
},
before: async () => {
prompts.inject([true]);
},
checks: checkPackgeAndPostcssConfig,
}),
},
],
}); });

79
src/tests/test-helpers.spec.ts

@ -20,10 +20,10 @@ export const createDefaultNbxConfig = async () => {
filesystem.write('.nbxrc', { git: { user: 'aaa', email: 'bbb' } }); filesystem.write('.nbxrc', { git: { user: 'aaa', email: 'bbb' } });
}; };
export const initWithConfigAndCommit = async () => {
export const initWithConfigAndCommit = async (packageJson = {}) => {
await system.run('git init'); await system.run('git init');
await createDefaultNbxConfig(); await createDefaultNbxConfig();
filesystem.write('package.json', {});
filesystem.write('package.json', packageJson);
await system.run('touch yarn.lock'); await system.run('touch yarn.lock');
await system.run('echo node_modules > .gitignore'); await system.run('echo node_modules > .gitignore');
await system.run('git add * .nbxrc .gitignore'); await system.run('git add * .nbxrc .gitignore');
@ -36,16 +36,18 @@ export const initWithConfigAndCommit = async () => {
export const expectGitCommits = ({ export const expectGitCommits = ({
before, before,
args,
expectGitLog, expectGitLog,
checks, checks,
args = [],
packageJson = {},
}: { }: {
args: string[];
args?: string[];
expectGitLog: string[] | (() => Promise<any>); expectGitLog: string[] | (() => Promise<any>);
before?: () => Promise<any>; before?: () => Promise<any>;
checks?: () => Promise<any>; checks?: () => Promise<any>;
packageJson?: object;
}): TestRun => async ({ exec, defaultArgs = [] }) => { }): TestRun => async ({ exec, defaultArgs = [] }) => {
await initWithConfigAndCommit();
await initWithConfigAndCommit(packageJson);
await before?.(); await before?.();
try { try {
@ -84,20 +86,73 @@ export const expectGitCommits = ({
await checks?.(); await checks?.();
}; };
export const expectFailGitCommits = ({
before,
args = [],
checks,
errorMessage,
packageJson = {},
}: {
args?: string[];
errorMessage: string;
before?: () => Promise<any>;
checks?: () => Promise<any>;
packageJson?: object;
}): TestRun => async ({ exec, defaultArgs = [] }) => {
expect.assertions(5);
await initWithConfigAndCommit(packageJson);
try {
await before?.();
await exec([...args, ...defaultArgs]);
// eslint-disable-next-line unicorn/catch-error-name
} catch (e) {
expect(e).toBeDefined();
expect(e.message).toBeDefined();
expect(e.message).toBe(errorMessage);
}
const after = await system.run('git log --name-status --format="%s"');
const afterSlitted = after
.split('\n')
.map(val => val.trim())
.map(val => stripANSI(val))
.filter(val => val !== '');
expect(afterSlitted).toStrictEqual([
'init state',
'A\t.gitignore',
'A\t.nbxrc',
'A\tpackage.json',
'A\tyarn.lock',
]);
await checks?.();
};
export const expectFailCli = ({ export const expectFailCli = ({
assertions = 4, assertions = 4,
before, before,
args,
args = [],
errorMessage, errorMessage,
withGitSetup = false,
packageJson = {},
}: { }: {
assertions?: number; assertions?: number;
before?: () => Promise<any>; before?: () => Promise<any>;
args: string[];
args?: string[];
errorMessage: string; errorMessage: string;
withGitSetup?: boolean;
packageJson?: object;
}): TestRun => async ({ exec, defaultArgs = [] }) => { }): TestRun => async ({ exec, defaultArgs = [] }) => {
expect.assertions(assertions);
if (withGitSetup) {
await initWithConfigAndCommit(packageJson);
}
try { try {
await before?.();
if (before) {
await before();
}
await exec([...args, ...defaultArgs]); await exec([...args, ...defaultArgs]);
// eslint-disable-next-line unicorn/catch-error-name // eslint-disable-next-line unicorn/catch-error-name
@ -148,6 +203,6 @@ export const testCli = ({ tests, runCommand, name, defaultArgs }: TestCliParams)
}); });
}; };
const testHelp = (command: Command) => {
it('');
};
test('testUtils should compile', () => {
expect(true).toBeTruthy();
});
Loading…
Cancel
Save