Skip to content
This repository has been archived by the owner on Jan 5, 2022. It is now read-only.

Commit

Permalink
Improve tests (#50)
Browse files Browse the repository at this point in the history
* Add missing `await`s

* Adjust tests

* Update test with nicer syntax

* Fix init test

* Add missing snapshot
  • Loading branch information
Florian Richter authored Jan 10, 2020
1 parent eecdf6b commit 0a4baeb
Show file tree
Hide file tree
Showing 17 changed files with 67 additions and 119 deletions.
6 changes: 3 additions & 3 deletions src/commands/add-approuter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ export default class AddApprouter extends Command {
const tasks = new Listr([
{
title: 'Creating files',
task: () => {
task: async () => {
const copyDescriptors = getCopyDescriptors(projectDir, getTemplatePaths(['add-approuter']));
findConflicts(copyDescriptors, flags.force);
copyFiles(copyDescriptors, options);
await findConflicts(copyDescriptors, flags.force).catch(e => this.error(e, { exit: 11 }));
await copyFiles(copyDescriptors, options);
}
}
]);
Expand Down
11 changes: 6 additions & 5 deletions src/commands/add-cds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,19 +52,20 @@ export default class AddCds extends Command {
const tasks = new Listr([
{
title: 'Creating files',
task: () => {
task: async () => {
const copyDescriptors = getCopyDescriptors(projectDir, getTemplatePaths(['add-cds']));
findConflicts(copyDescriptors, flags.force);
copyFiles(copyDescriptors, options);
await findConflicts(copyDescriptors, flags.force).catch(e => this.error(e, { exit: 11 }));
await copyFiles(copyDescriptors, options);
}
},
{
title: 'Adding dependencies to package.json',
task: () => modifyPackageJson({ projectDir, force: flags.force, addCds: true })
task: async () => modifyPackageJson({ projectDir, force: flags.force, addCds: true }).catch(e => this.error(e, { exit: 12 }))
},
{
title: 'Installing dependencies',
task: () => installDependencies(projectDir, flags.verbose).catch(e => this.error(`Error during npm install: ${e.message}`, { exit: 13 })),
task: async () =>
installDependencies(projectDir, flags.verbose).catch(e => this.error(`Error during npm install: ${e.message}`, { exit: 13 })),
enabled: () => !flags.skipInstall
},
{
Expand Down
4 changes: 2 additions & 2 deletions src/commands/add-cx-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ export default class AddCxServer extends Command {
const tasks = new Listr([
{
title: 'Finding potential conflicts',
task: () => findConflicts(files, flags.force)
task: async () => findConflicts(files, flags.force).catch(e => this.error(e, { exit: 11 }))
},
{
title: 'Creating files',
task: () => copyFiles(files, options)
task: async () => copyFiles(files, options)
}
]);

Expand Down
4 changes: 2 additions & 2 deletions src/commands/help-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*/

import { Command } from '@oclif/command';
import cli from 'cli-ux';
import * as execa from 'execa';

export default class HelpPage extends Command {
static description = 'Display the product page, which contains tutorials and links to all relevant resources';
Expand All @@ -13,6 +13,6 @@ export default class HelpPage extends Command {
this.log(' https://community.sap.com/topics/cloud-sdk');
this.log(' https://developers.sap.com/topics/cloud-sdk.html');

await cli.open('https://community.sap.com/topics/cloud-sdk');
await execa('open', ['https://community.sap.com/topics/cloud-sdk']);
}
}
16 changes: 10 additions & 6 deletions src/commands/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,10 @@ export default class Init extends Command {
const tasks = new Listr([
{
title: 'Creating files',
task: () => {
task: async () => {
const copyDescriptors = getCopyDescriptors(projectDir, getTemplatePaths(this.getTemplateNames(isScaffold, flags.addCds)));
findConflicts(copyDescriptors, flags.force);
copyFiles(copyDescriptors, options);
await findConflicts(copyDescriptors, flags.force).catch(e => this.error(e, { exit: 11 }));
await copyFiles(copyDescriptors, options);
}
},
{
Expand All @@ -116,11 +116,15 @@ export default class Init extends Command {
},
{
title: 'Adding dependencies to package.json',
task: () => modifyPackageJson({ projectDir, isScaffold, frontendScripts: flags.frontendScripts, force: flags.force, addCds: flags.addCds })
task: async () =>
modifyPackageJson({ projectDir, isScaffold, frontendScripts: flags.frontendScripts, force: flags.force, addCds: flags.addCds }).catch(e =>
this.error(e, { exit: 12 })
)
},
{
title: 'Installing dependencies',
task: () => installDependencies(projectDir, flags.verbose).catch(e => this.error(`Error during npm install: ${e.message}`, { exit: 13 })),
task: async () =>
installDependencies(projectDir, flags.verbose).catch(e => this.error(`Error during npm install: ${e.message}`, { exit: 13 })),
enabled: () => !flags.skipInstall
},
{
Expand Down Expand Up @@ -154,7 +158,7 @@ export default class Init extends Command {
}

private async getOptions(projectDir: string, startCommand?: string, projectName?: string) {
const { name, scripts } = parsePackageJson(projectDir);
const { name, scripts } = await parsePackageJson(projectDir).catch(err => this.error(err, { exit: 10 }));

const options: { [key: string]: string } = {
projectName:
Expand Down
12 changes: 5 additions & 7 deletions src/utils/package-json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved.
*/

import cli from 'cli-ux';
import * as execa from 'execa';
import * as fs from 'fs';
import * as path from 'path';
Expand Down Expand Up @@ -61,15 +60,15 @@ const existingProjectPackageJson: PackageJsonChange = {
dependencies: ['@sap/cloud-sdk-core']
};

export function parsePackageJson(projectDir: string) {
export async function parsePackageJson(projectDir: string) {
try {
return JSON.parse(
fs.readFileSync(path.resolve(projectDir, 'package.json'), {
encoding: 'utf8'
})
);
} catch (error) {
return cli.error('Your package.json does not contain valid JSON. Please repair or delete it.', { exit: 10 });
throw new Error('Your package.json does not contain valid JSON. Please repair or delete it.');
}
}

Expand Down Expand Up @@ -131,16 +130,15 @@ export async function modifyPackageJson({
force?: boolean;
addCds?: boolean;
}) {
const originalPackageJson = parsePackageJson(projectDir);
const originalPackageJson = await parsePackageJson(projectDir);
const changes = await getPackageJsonChanges(isScaffold, frontendScripts, addCds);
const conflicts = findScriptConflicts(originalPackageJson.scripts, changes.scripts);

if (conflicts.length && !force) {
return cli.error(
throw new Error(
conflicts.length > 1
? `Scripts with the names "${conflicts.join('", "')}" already exist. If you want to overwrite them, rerun the command with \`--force\`.`
: `A script with the name "${conflicts.join('", "')}" already exists. If you want to overwrite it, rerun the command with \`--force\`.`,
{ exit: 12 }
: `A script with the name "${conflicts.join('", "')}" already exists. If you want to overwrite it, rerun the command with \`--force\`.`
);
}

Expand Down
6 changes: 2 additions & 4 deletions src/utils/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved.
*/

import cli from 'cli-ux';
import * as fs from 'fs';
import { compile } from 'handlebars';
import * as https from 'https';
Expand Down Expand Up @@ -62,11 +61,10 @@ export async function findConflicts(copyDescriptors: CopyDescriptor[], force = f
conflicts.forEach(copyDescriptor => fs.unlinkSync(copyDescriptor.fileName));
} else {
const listOfFiles = conflicts.map(f => path.basename(f.fileName)).join('", "');
cli.error(
throw new Error(
conflicts.length > 1
? `Files with the names "${listOfFiles}" already exist. If you want to overwrite them, rerun the command with \`--force\`.`
: `A file with the name "${listOfFiles}" already exists. If you want to overwrite it, rerun the command with \`--force\`.`,
{ exit: 1 }
: `A file with the name "${listOfFiles}" already exists. If you want to overwrite it, rerun the command with \`--force\`.`
);
}
}
Expand Down
3 changes: 3 additions & 0 deletions test/__snapshots__/add-approuter.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Add Approuter should detect and fail if there are conflicts 1`] = `[Error: A file with the name "xs-security.json" already exists. If you want to overwrite it, rerun the command with \`--force\`.]`;
3 changes: 3 additions & 0 deletions test/__snapshots__/add-cds.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Add CDS should detect and fail if there are conflicts 1`] = `[Error: A file with the name "data-model.cds" already exists. If you want to overwrite it, rerun the command with \`--force\`.]`;
3 changes: 3 additions & 0 deletions test/__snapshots__/add-cx-server.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Add CX Server should detect and fail if there are conflicts 1`] = `[Error: A file with the name "cx-server" already exists. If you want to overwrite it, rerun the command with \`--force\`.]`;
3 changes: 3 additions & 0 deletions test/__snapshots__/init.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Init init should detect and fail if there are conflicts 1`] = `[Error: A file with the name ".npmrc" already exists. If you want to overwrite it, rerun the command with \`--force\`.]`;
15 changes: 2 additions & 13 deletions test/add-approuter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,16 @@
*/

const prompt = jest.fn().mockResolvedValue('mock-project');
const error = jest.fn();
jest.mock('cli-ux', () => {
// Mocking needs to happen before the command is imported
const cli = jest.requireActual('cli-ux');
return {
...cli,
default: {
...cli.default,
prompt,
error
prompt
}
};
});

import * as fs from 'fs-extra';
import * as path from 'path';
import AddApprouter from '../src/commands/add-approuter';
Expand Down Expand Up @@ -71,13 +67,6 @@ describe('Add Approuter', () => {
fs.createFileSync(path.resolve(projectDir, 'approuter', 'xs-security.json'));
fs.writeFileSync(path.resolve(projectDir, 'approuter', 'xs-security.json'), JSON.stringify({ 'tenant-mode': 'shared' }), 'utf8');

await AddApprouter.run([projectDir]);

expect(error).toHaveBeenCalledWith(
'A file with the name "xs-security.json" already exists. If you want to overwrite it, rerun the command with `--force`.',
{
exit: 1
}
);
await expect(AddApprouter.run([projectDir])).rejects.toMatchSnapshot();
});
});
13 changes: 2 additions & 11 deletions test/add-cds.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,14 @@
*/

const prompt = jest.fn().mockResolvedValue('mock-project');
const error = jest.fn();
jest.mock('cli-ux', () => {
// Mocking needs to happen before the command is imported
const cli = jest.requireActual('cli-ux');
return {
...cli,
default: {
...cli.default,
prompt,
error
prompt
}
};
});
Expand Down Expand Up @@ -54,13 +52,6 @@ describe('Add CDS', () => {
fs.createFileSync(path.resolve(projectDir, 'db', 'data-model.cds'));
fs.writeFileSync(path.resolve(projectDir, 'db', 'data-model.cds'), 'some text', 'utf8');

await AddCds.run([projectDir, '--skipInstall']);

expect(error).toHaveBeenCalledWith(
'A file with the name "data-model.cds" already exists. If you want to overwrite it, rerun the command with `--force`.',
{
exit: 1
}
);
await expect(AddCds.run([projectDir, '--skipInstall'])).rejects.toMatchSnapshot();
}, 10000);
});
22 changes: 1 addition & 21 deletions test/add-cx-server.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,6 @@
* Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved.
*/

const error = jest.fn();
jest.mock('cli-ux', () => {
// Mocking needs to happen before the command is imported
const cli = jest.requireActual('cli-ux');
return {
...cli,
default: {
...cli.default,
error
}
};
});

import * as fs from 'fs-extra';
import * as path from 'path';
import AddCxServer from '../src/commands/add-cx-server';
Expand Down Expand Up @@ -75,13 +62,6 @@ describe('Add CX Server', () => {
fs.mkdirSync(path.resolve(projectDir, 'cx-server'), { recursive: true });
fs.createFileSync(path.resolve(projectDir, 'cx-server', 'cx-server'));

await AddCxServer.run([projectDir]);

expect(error).toHaveBeenCalledWith(
'A file with the name "cx-server" already exists. If you want to overwrite it, rerun the command with `--force`.',
{
exit: 1
}
);
await expect(AddCxServer.run([projectDir])).rejects.toMatchSnapshot();
}, 30000);
});
35 changes: 12 additions & 23 deletions test/generate-odata-client.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,35 +22,28 @@ describe('generate-odata-client', () => {
});

it('should fail if the mandatory parameters are not there', async () => {
try {
await GenerateODataClient.run([]);
} catch (e) {
expect(e.message).toContain('-i, --inputDir INPUTDIR');
}
await expect(GenerateODataClient.run([])).rejects.toThrowError('-i, --inputDir INPUTDIR');
});

it('should parse strings and with --no- it should lead to all false.', async () => {
const expected = getParsedInputWithAllBooleanFlagsFalse();
delete expected.projectDir;
try {
await GenerateODataClient.run([...getCliInputWithAllBooleanFlagsFalse(), '--projectDir', getProjectDir()]);
} catch (e) {
expect(e.message).toContain('ENOENT: no such file or directory');
expect(spyToGeneratorSDK).toHaveReturnedWith(expected);
}

await expect(GenerateODataClient.run([...getCliInputWithAllBooleanFlagsFalse(), '--projectDir', getProjectDir()])).rejects.toThrowError(
'ENOENT: no such file or directory'
);
expect(spyToGeneratorSDK).toHaveReturnedWith(expected);
});

it('should resolve the projectdir', async () => {
// TODO there was a issue in the SDK for the service-mapping.json file and windows. Onve the fix is out put this test back int.
if (process.platform !== 'win32') {
const expected = getDefault(getProjectDir());

try {
await GenerateODataClient.run(['-i', 'input', '-o', 'output', '--projectDir', getProjectDir()]);
} catch (e) {
expect(e.message).toContain('ENOENT: no such file or directory');
expect(spyToGeneratorSDK).toHaveReturnedWith(expected);
}
await expect(GenerateODataClient.run(['-i', 'input', '-o', 'output', '--projectDir', getProjectDir()])).rejects.toThrowError(
'ENOENT: no such file or directory'
);
expect(spyToGeneratorSDK).toHaveReturnedWith(expected);
}
});

Expand All @@ -77,12 +70,8 @@ describe('generate-odata-client', () => {
for (const key of Object.keys(generatorOptionsSDK)) {
const argsExpected = getInputAndExpected(key as keyof GeneratorOptionsSDK);
if (argsExpected) {
try {
await GenerateODataClient.run(argsExpected.args);
} catch (e) {
expect(e.message).toContain('ENOENT: no such file or directory');
expect(spyToGeneratorSDK).toHaveReturnedWith(argsExpected.expected);
}
await expect(GenerateODataClient.run(argsExpected.args)).rejects.toThrowError('ENOENT: no such file or directory');
expect(spyToGeneratorSDK).toHaveReturnedWith(argsExpected.expected);
}
}
}
Expand Down
22 changes: 4 additions & 18 deletions test/init.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,7 @@
/*!
* Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved.
*/
const error = jest.fn();
jest.mock('cli-ux', () => {
// Mocking needs to happen before the command is imported
const cli = jest.requireActual('cli-ux');
return {
...cli,
default: {
...cli.default,
error
}
};
});

jest.mock('../src/utils/warnings');

import execa = require('execa');
Expand Down Expand Up @@ -100,12 +89,9 @@ describe('Init', () => {
fs.copySync(nestAppDir, projectDir, { recursive: true });
fs.createFileSync(`${projectDir}/.npmrc`);

await Init.run([projectDir, '--projectName=testingApp', '--startCommand="npm start"', '--skipInstall', '--no-analytics']);

expect(error).toHaveBeenCalledWith(
'A file with the name ".npmrc" already exists. If you want to overwrite it, rerun the command with `--force`.',
{ exit: 1 }
);
await expect(
Init.run([projectDir, '--projectName=testingApp', '--startCommand="npm start"', '--skipInstall', '--no-analytics'])
).rejects.toMatchSnapshot();
}, 10000);

it('should add to .gitignore if there is one', async () => {
Expand Down
Loading

0 comments on commit 0a4baeb

Please sign in to comment.