Skip to content

Commit

Permalink
feat: add testing to all generator use cases
Browse files Browse the repository at this point in the history
  • Loading branch information
mcfdez committed Feb 20, 2024
1 parent cbb0caa commit 235ad5f
Show file tree
Hide file tree
Showing 13 changed files with 425 additions and 5 deletions.
55 changes: 55 additions & 0 deletions plugin/tests/executors/compiler/executor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { exec } from 'child_process';
import { CompileExecutorSchema } from './schema';

/**
* Execute a command and return a promise
*
* @param cmd The command to execute
*
* @returns A promise that resolves with the output of the command
*/
export function execPromise(cmd: string): Promise<string> {
return new Promise((resolve, reject) => {
const response = exec(cmd, (err, data) => {
response.removeAllListeners();

if (err) {
reject(err);
return;
}

resolve(data);
});

response.stdout.on('data', (data) => {
console.log(data);
});

response.stderr.on('data', (data) => {
console.error(data);
});
});
}

/**
* Run the compile executor
*
* @param options The options for the compile executor
*/
export default async function runExecutor(options: CompileExecutorSchema) {
let sassCommand = `sass ${options.main} ${options.outputPath}/styles.css`;

if (!options.sourceMap) {
sassCommand += ' --no-source-map';
}

if (options.watch) {
sassCommand += ' --watch';
}

await execPromise(sassCommand);

return {
success: true,
};
}
9 changes: 9 additions & 0 deletions plugin/tests/executors/compiler/schema.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* Schema for the compile executor options
*/
export interface CompileExecutorSchema {
outputPath: string;
main: string;
sourceMap: boolean;
watch: boolean;
}
21 changes: 21 additions & 0 deletions plugin/tests/executors/compiler/schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"$schema": "http://json-schema.org/schema",
"title": "Schema for Nx sass-compiler executor",
"description": "Compiles Sass files to CSS using Sass",
"type": "object",
"properties": {
"outputPath": {
"type": "string",
"description": "The output path of a project's build. Relative to the root of the repository."
},
"main": {
"type": "string",
"description": "The main file to compile"
},
"sourceMap": {
"type": "boolean",
"description": "Generate source maps"
}
},
"required": ["outputPath"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Tree, addDependenciesToPackageJson } from '@nx/devkit';
import addDependencies from '../../../../src/generators/library/application/add-dependencies.use-case';

jest.mock('@nx/devkit', () => ({
...jest.requireActual('@nx/devkit'),
addDependenciesToPackageJson: jest.fn(),
}));

describe('addDependencies', () => {
it('should call addDependenciesToPackageJson with the correct arguments', () => {
const tree = {} as Tree;

addDependencies(tree);

expect(addDependenciesToPackageJson).toHaveBeenCalledWith(
tree,
{},
{
sass: '1.71.0',
stylelint: '16.2.1',
'stylelint-config-standard-scss': '13.0.0',
'nx-stylelint': '17.1.4',
},
undefined,
false,
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Tree, writeJson } from '@nx/devkit';
import { createTreeWithEmptyWorkspace } from 'nx/src/devkit-testing-exports';
import addStylelintConfig from '../../../../src/generators/library/application/add-stylelint-config.use-case';
import { NormalizedSchema } from '../../../../src/generators/library/domain/normalized-schema';

jest.mock('@nx/devkit', () => ({
...jest.requireActual('@nx/devkit'),
writeJson: jest.fn(),
}));

describe('addStylelintConfig', () => {
let appTree: Tree;
const options: NormalizedSchema = { name: 'test', directory: 'my-library' };

beforeEach(() => {
appTree = createTreeWithEmptyWorkspace({ layout: 'apps-libs' });
});

it('should write the Stylelint configuration file with the correct data', () => {
addStylelintConfig(appTree, options);

expect(writeJson).toHaveBeenCalledWith(
appTree,
'libs/my-library/.stylelintrc.json',
{
extends: ['../../.stylelintrc.json'],
ignoreFiles: ['!**/*'],
overrides: [
{
files: ['**/*.scss'],
rules: {},
},
],
},
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Tree, writeJson } from '@nx/devkit';
import { createTreeWithEmptyWorkspace } from 'nx/src/devkit-testing-exports';
import addStylelintRootConfig from '../../../../src/generators/library/application/add-stylelint-root-config.use-case';

jest.mock('@nx/devkit', () => ({
...jest.requireActual('@nx/devkit'),
writeJson: jest.fn(),
}));

describe('addStylelintRootConfig', () => {
let appTree: Tree;

beforeEach(() => {
appTree = createTreeWithEmptyWorkspace({ layout: 'apps-libs' });
});

it('should write the Stylelint root configuration file with the correct data', () => {
addStylelintRootConfig(appTree);

expect(writeJson).toHaveBeenCalledWith(
appTree,
'.stylelintrc.json',
{
ignoreFiles: ['**/*'],
overrides: [
{
files: ['**/*.scss'],
extends: ['stylelint-config-standard-scss'],
rules: {},
},
],
rules: {},
},
);
});
});
32 changes: 32 additions & 0 deletions plugin/tests/generators/library/application/create-files.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Tree, generateFiles } from '@nx/devkit';
import { createTreeWithEmptyWorkspace } from 'nx/src/devkit-testing-exports';
import createFiles from '../../../../src/generators/library/application/create-files.use-case';
import { NormalizedSchema } from '../../../../src/generators/library/domain/normalized-schema';

jest.mock('@nx/devkit', () => ({
...jest.requireActual('@nx/devkit'),
generateFiles: jest.fn(),
}));

describe('createFiles', () => {
let appTree: Tree;
const options: NormalizedSchema = { name: 'test', directory: 'my-library' };

beforeEach(() => {
appTree = createTreeWithEmptyWorkspace({ layout: 'apps-libs' });
});

it('should generate files for the library with the correct substitutions', async () => {
await createFiles(appTree, options);

expect(generateFiles).toHaveBeenCalledWith(
appTree,
expect.any(String),
'libs/my-library',
{
appName: 'test',
style: 'scss',
},
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { Tree, addProjectConfiguration } from '@nx/devkit';
import { createTreeWithEmptyWorkspace } from 'nx/src/devkit-testing-exports';
import createProjectConfiguration from '../../../../src/generators/library/application/create-project-configuration.use-case';
import { NormalizedSchema } from '../../../../src/generators/library/domain/normalized-schema';

jest.mock('@nx/devkit', () => ({
...jest.requireActual('@nx/devkit'),
addProjectConfiguration: jest.fn(),
}));

describe('createProjectConfiguration', () => {
let appTree: Tree;
const options: NormalizedSchema = { name: 'test', directory: 'my-library' };

beforeEach(() => {
appTree = createTreeWithEmptyWorkspace({ layout: 'apps-libs' });
});

it('should create a new project configuration in the workspace', () => {
createProjectConfiguration(appTree, options);

expect(addProjectConfiguration).toHaveBeenCalledWith(
appTree,
'test',
{
name: 'test',
projectType: 'library',
root: 'libs/my-library',
sourceRoot: 'libs/my-library',
targets: {
build: {
executor: 'nx-sass:compiler',
outputs: ['{options.outputPath}'],
options: {
outputPath: 'dist',
main: 'libs/my-library/src/main.scss',
sourceMap: true,
},
configurations: {
production: {},
development: {},
},
defaultConfiguration: 'production',
},
serve: {
executor: 'nx-sass:compiler',
options: {
watch: true,
outputPath: 'dist',
main: 'libs/my-library/src/main.scss',
sourceMap: true,
},
},
lint: {
executor: 'nx-stylelint:lint',
outputs: ['{options.outputFile}'],
options: {
lintFilePatterns: ['libs/my-library/src/**/*.scss'],
formatter: 'compact',
},
},
},
},
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Tree } from '@nx/devkit';
import { determineProjectNameAndRootOptions } from '@nx/devkit/src/generators/project-name-and-root-utils';
import { createTreeWithEmptyWorkspace } from 'nx/src/devkit-testing-exports';
import normalizeOptions from '../../../../src/generators/library/application/normalize-options.use-case';
import { NormalizedSchema } from '../../../../src/generators/library/domain/normalized-schema';

jest.mock('@nx/devkit/src/generators/project-name-and-root-utils', () => ({
...jest.requireActual('@nx/devkit/src/generators/project-name-and-root-utils'),
determineProjectNameAndRootOptions: jest.fn().mockResolvedValue({ projectName: 'appProjectName' }),
}));

describe('normalizeOptions', () => {
let appTree: Tree;
const options: NormalizedSchema = { name: 'test', directory: 'my-library' };

beforeEach(() => {
appTree = createTreeWithEmptyWorkspace({ layout: 'apps-libs' });
});

it('should normalize the options correctly', async () => {
const normalizedOptions: NormalizedSchema = await normalizeOptions(appTree, options);

expect(determineProjectNameAndRootOptions).toHaveBeenCalledWith(appTree, {
name: 'test',
projectType: 'library',
directory: 'my-library',
callingGenerator: 'nx-sass:library',
});

expect(normalizedOptions).toEqual({
name: 'appProjectName',
directory: 'my-library',
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Tree, readNxJson, updateNxJson } from '@nx/devkit';
import { createTreeWithEmptyWorkspace } from 'nx/src/devkit-testing-exports';
import setGeneratorDefaults from '../../../../src/generators/library/application/set-generator-defaults.use-case';

jest.mock('@nx/devkit');

describe('setGeneratorDefaults', () => {
let appTree: Tree;

beforeEach(() => {
appTree = createTreeWithEmptyWorkspace({ layout: 'apps-libs' });
});

it('should set generator defaults', () => {
const mockNxJson = {
generators: {
'nx-sass:library': {},
},
};

(readNxJson as jest.Mock).mockReturnValueOnce(mockNxJson);

setGeneratorDefaults(appTree);

expect(readNxJson).toHaveBeenCalledWith(appTree);
expect(updateNxJson).toHaveBeenCalledWith(appTree, {
...mockNxJson,
generators: {
...(mockNxJson.generators || {}),
'nx-sass:library': {},
},
});
});

it('should create generator configuration if none exists', () => {
const mockNxJson = {};

(readNxJson as jest.Mock).mockReturnValueOnce(mockNxJson);

setGeneratorDefaults(appTree);

expect(readNxJson).toHaveBeenCalledWith(appTree);
expect(updateNxJson).toHaveBeenCalledWith(appTree, {
generators: {
'nx-sass:library': {},
},
});
});
});
Loading

0 comments on commit 235ad5f

Please sign in to comment.