Skip to content

Commit

Permalink
fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
BioPhoton committed Dec 10, 2024
1 parent e1f5f93 commit f8043e1
Show file tree
Hide file tree
Showing 10 changed files with 109 additions and 93 deletions.
5 changes: 2 additions & 3 deletions e2e/nx-verdaccio-e2e/setup/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ import {
updateJson,
} from '@push-based/test-utils';
import { dirname, join } from 'node:path';
import { copyFile, cp, mkdir, readFile, writeFile } from 'node:fs/promises';
import { copyFile, mkdir } from 'node:fs/promises';
import { logger, NxJsonConfiguration } from '@nx/devkit';
import { PackageJson } from 'nx/src/utils/package-json';
import { NxJson } from 'nx/src/native';

export async function setup({
envRoot,
Expand Down Expand Up @@ -95,7 +94,7 @@ export async function setup({
await updateJson<NxJsonConfiguration>(join(envRoot, 'nx.json'), (json) => ({
...json,
plugins: [
...json?.plugins,
...(json?.plugins ?? {}),
{
plugin: '@push-based/nx-verdaccio',
options: {
Expand Down
12 changes: 1 addition & 11 deletions e2e/nx-verdaccio-e2e/test/target-env-setup.e2e.test.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,10 @@
import type { Tree } from '@nx/devkit';
import { join } from 'node:path';
import { afterEach, expect } from 'vitest';
import {
addJsLibToWorkspace,
materializeTree,
registerPluginInWorkspace,
} from '@push-based/test-nx-utils';
import { updateProjectConfiguration } from 'nx/src/generators/utils/project-configuration';
import { executeProcess, teardownTestFolder } from '@push-based/test-utils';
import { executeProcess } from '@push-based/test-utils';
import { TARGET_ENVIRONMENT_SETUP } from '@push-based/nx-verdaccio';

describe('nx-verdaccio plugin nxv-env-setup target', () => {
let tree: Tree;
const projectA = 'lib-a';
const projectAE2e = `${projectA}-e2e`;
const e2eProjectARoot = join('projects', projectAE2e);
const baseDir = `tmp/environments/${process.env['NX_TASK_TARGET_PROJECT']}/__test__/target-env-setup`;

afterEach(async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
type VercaddioServerResult,
} from './verdaccio-registry';
import { writeFile } from 'node:fs/promises';
import { setupNpmWorkspace } from './npm';
import { formatError, formatInfo } from '../../internal/logging';
import { VERDACCIO_REGISTRY_JSON } from './constants';
import { logger } from '@nx/devkit';
Expand All @@ -15,6 +14,7 @@ import {
type Environment,
VERDACCIO_ENV_TOKEN,
} from './npm';
import { setupNpmWorkspace } from '../env-setup/npm';

export type BootstrapEnvironmentOptions = StartVerdaccioOptions & Environment;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,6 @@ describe('bootstrapEnvironment', () => {
},
stop: vi.fn(),
});
const setupNpmWorkspaceSpy = vi
.spyOn(npmModule, 'setupNpmWorkspace')
.mockImplementation(vi.fn());
const configureRegistrySpy = vi
.spyOn(npmModule, 'configureRegistry')
.mockImplementation(vi.fn());
Expand Down Expand Up @@ -73,12 +70,6 @@ describe('bootstrapEnvironment', () => {
verbose: undefined,
});

expect(setupNpmWorkspaceSpy).toHaveBeenCalledTimes(1);
expect(setupNpmWorkspaceSpy).toHaveBeenCalledWith(
expect.toMatchPath('tmp/environments/my-lib-e2e'),
undefined
);

expect(configureRegistrySpy).toHaveBeenCalledTimes(1);
expect(configureRegistrySpy).toHaveBeenCalledWith(
{
Expand Down
36 changes: 2 additions & 34 deletions projects/nx-verdaccio/src/executors/env-bootstrap/npm.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { exec, execFile } from 'node:child_process';
import { join } from 'node:path';
import { exec } from 'node:child_process';
import { promisify } from 'node:util';
import { ensureDirectoryExists } from '../../internal/file-system';
import { formatError, formatInfo } from '../../internal/logging';
import { formatInfo } from '../../internal/logging';
import { logger } from '@nx/devkit';
import type { VercaddioServerResult } from './verdaccio-registry';
import { objectToCliArgs } from '../../internal/terminal';
Expand All @@ -18,36 +16,6 @@ export function chdir(path: string): void {
process.chdir(path);
}

export async function setupNpmWorkspace(
environmentRoot: string,
verbose?: boolean
): Promise<void> {
if (verbose) {
logger.info(
formatInfo(
`Execute: npm init in directory ${environmentRoot}`,
NPM_ENV_TOKEN
)
);
}
const cwd = process.cwd();
await ensureDirectoryExists(environmentRoot);
try {
await promisify(execFile)('npm', ['init', '--force'], {
shell: true,
windowsHide: true,
cwd: join(cwd, environmentRoot),
});
} catch (error) {
logger.error(
formatError(
`Error creating NPM workspace: ${(error as Error).message}`,
NPM_ENV_TOKEN
)
);
}
}

export const VERDACCIO_ENV_TOKEN = 'Verdaccio Env: ';

export type Environment = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import { MEMFS_VOLUME } from '@push-based/test-utils';
import {
configureRegistry,
type ConfigureRegistryOptions,
setupNpmWorkspace,
unconfigureRegistry,
VERDACCIO_ENV_TOKEN,
} from './npm';
import { logger } from '@nx/devkit';
import { formatInfo } from '../../internal/logging';
import { setupNpmWorkspace } from '../env-setup/npm';

const execMock = vi.fn();
vi.mock('util', () => ({
Expand Down Expand Up @@ -133,36 +133,3 @@ describe('unconfigureRegistry', () => {
);
});
});

describe.skip('setupNpmWorkspace', () => {
let cwdSpy;
let chdirSpy;
let consoleInfoSpy;

beforeEach(() => {
cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(MEMFS_VOLUME);
chdirSpy = vi.spyOn(process, 'chdir').mockImplementation(vi.fn());
consoleInfoSpy = vi.spyOn(console, 'info').mockImplementation(vi.fn());
});

afterEach(() => {
cwdSpy.mockRestore();
chdirSpy.mockRestore();
consoleInfoSpy.mockRestore();
});

it('should create npm workspace in given folder', async () => {
await setupNpmWorkspace('tmp');
expect(chdirSpy).toHaveBeenCalledTimes(1);
expect(chdirSpy).toHaveBeenCalledWith('tmp');
expect(consoleInfoSpy).not.toHaveBeenCalled();
});

it('should call infoLog if verbose is given', async () => {
await setupNpmWorkspace('tmp', true);
expect(consoleInfoSpy).toHaveBeenCalledTimes(1);
expect(consoleInfoSpy).toHaveBeenCalledWith(
`${red('>')} ${red(bold('Npm Env: '))} Execute: npm init in directory tmp`
);
});
});
3 changes: 2 additions & 1 deletion projects/nx-verdaccio/src/executors/env-setup/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ import {
import { runSingleExecutor } from '../../internal/run-executor';
import { getEnvironmentRoot } from '../../internal/environment-root';
import { cleanupEnv } from '../internal/cleanup-env';
import { setupNpmWorkspace } from '../env-bootstrap/npm';

import { setupNpmWorkspace } from './npm';

export type ExecutorOutput = {
success: boolean;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
TARGET_ENVIRONMENT_VERDACCIO_STOP,
} from '../../plugin/targets/environment.targets';
import { MockAsyncIterableIterator } from '@push-based/test-utils';
import * as npmModule from './npm';

vi.mock('@nx/devkit', async () => {
const actual = await vi.importActual('@nx/devkit');
Expand Down Expand Up @@ -38,6 +39,7 @@ vi.mock('fs/promises', async () => {
describe('runSetupEnvironmentExecutor', () => {
const runExecutorSpy = vi.spyOn(devkit, 'runExecutor');
const executeProcessSpy = vi.spyOn(executeProcessModule, 'executeProcess');
const setupNpmWorkspaceSpy = vi.spyOn(npmModule, 'setupNpmWorkspace');

beforeEach(() => {
runExecutorSpy.mockReset();
Expand Down Expand Up @@ -122,6 +124,12 @@ describe('runSetupEnvironmentExecutor', () => {
},
context
);

expect(setupNpmWorkspaceSpy).toHaveBeenCalledTimes(1);
expect(setupNpmWorkspaceSpy).toHaveBeenCalledWith(
expect.toMatchPath('tmp/environments/my-lib-e2e'),
undefined
);
});

it('should catch error cause by runBootstrapEnvironment', async () => {
Expand Down
37 changes: 37 additions & 0 deletions projects/nx-verdaccio/src/executors/env-setup/npm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { logger } from '@nx/devkit';
import { formatError, formatInfo } from '../../internal/logging';
import { ensureDirectoryExists } from '../../internal/file-system';
import { promisify } from 'node:util';
import { execFile } from 'node:child_process';
import { join } from 'node:path';
import { NPM_ENV_TOKEN } from '../env-bootstrap/npm';

export async function setupNpmWorkspace(
environmentRoot: string,
verbose?: boolean
): Promise<void> {
if (verbose) {
logger.info(
formatInfo(
`Execute: npm init in directory ${environmentRoot}`,
NPM_ENV_TOKEN
)
);
}
const cwd = process.cwd();
await ensureDirectoryExists(environmentRoot);
try {
await promisify(execFile)('npm', ['init', '--force'], {
shell: true,
windowsHide: true,
cwd: join(cwd, environmentRoot),
});
} catch (error) {
logger.error(
formatError(
`Error creating NPM workspace: ${(error as Error).message}`,
NPM_ENV_TOKEN
)
);
}
}
55 changes: 55 additions & 0 deletions projects/nx-verdaccio/src/executors/env-setup/npm.unit-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { bold, red } from 'ansis';
import { MEMFS_VOLUME } from '@push-based/test-utils';
import {
configureRegistry,
type ConfigureRegistryOptions,
unconfigureRegistry,
VERDACCIO_ENV_TOKEN,
} from './npm';
import { logger } from '@nx/devkit';
import { formatInfo } from '../../internal/logging';
import { setupNpmWorkspace } from '../env-setup/npm';

vi.mock('@nx/devkit', async () => {
const actual = await vi.importActual('@nx/devkit');
return {
...actual,
logger: {
info: vi.fn(),
},
};
});

describe.skip('setupNpmWorkspace', () => {
let cwdSpy;
let chdirSpy;
let consoleInfoSpy;

beforeEach(() => {
cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(MEMFS_VOLUME);
chdirSpy = vi.spyOn(process, 'chdir').mockImplementation(vi.fn());
consoleInfoSpy = vi.spyOn(console, 'info').mockImplementation(vi.fn());
});

afterEach(() => {
cwdSpy.mockRestore();
chdirSpy.mockRestore();
consoleInfoSpy.mockRestore();
});

it('should create npm workspace in given folder', async () => {
await setupNpmWorkspace('tmp');
expect(chdirSpy).toHaveBeenCalledTimes(1);
expect(chdirSpy).toHaveBeenCalledWith('tmp');
expect(consoleInfoSpy).not.toHaveBeenCalled();
});

it('should call infoLog if verbose is given', async () => {
await setupNpmWorkspace('tmp', true);
expect(consoleInfoSpy).toHaveBeenCalledTimes(1);
expect(consoleInfoSpy).toHaveBeenCalledWith(
`${red('>')} ${red(bold('Npm Env: '))} Execute: npm init in directory tmp`
);
});
});

0 comments on commit f8043e1

Please sign in to comment.