Skip to content

Commit

Permalink
test: fix test execution for nx v19
Browse files Browse the repository at this point in the history
  • Loading branch information
llwt committed Sep 11, 2024
1 parent ae4f9bd commit 853ee00
Show file tree
Hide file tree
Showing 13 changed files with 212 additions and 167 deletions.
18 changes: 18 additions & 0 deletions apps/nx-workshop-e2e/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
14 changes: 0 additions & 14 deletions apps/nx-workshop-e2e/jest.config.js

This file was deleted.

9 changes: 9 additions & 0 deletions apps/nx-workshop-e2e/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/* eslint-disable */
export default {
displayName: 'nx-workshop-e2e',
preset: '../../jest.preset.js',
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../coverage/apps/nx-workshop-e2e',
globalSetup: '../../tools/scripts/start-local-registry.ts',
globalTeardown: '../../tools/scripts/stop-local-registry.ts',
};
21 changes: 8 additions & 13 deletions apps/nx-workshop-e2e/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,18 @@
"tags": [],
"implicitDependencies": ["nx-react-workshop"],
"targets": {
"build-migrations": {
"executor": "nx:run-commands",
"options": {
"commands": [
"npx nx build nx-react-workshop",
"cp -R dist/libs/nx-react-workshop/* tmp/nx-e2e/proj/node_modules/@nrwl/nx-react-workshop"
]
}
},
"e2e": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "apps/nx-workshop-e2e/jest.config.js",
"runInBand": true,
"passWithNoTests": false
"jestConfig": "apps/nx-workshop-e2e/jest.config.ts",
"runInBand": true
},
"dependsOn": ["nx-react-workshop:build"]
"dependsOn": ["^build"]
},

"lint": {
"executor": "@nx/eslint:lint"
}
}
}
182 changes: 97 additions & 85 deletions apps/nx-workshop-e2e/tests/nx-workshop.spec.ts
Original file line number Diff line number Diff line change
@@ -1,112 +1,124 @@
import { readJsonFile, workspaceRoot, writeJsonFile } from '@nx/devkit';
import { ExecSyncOptionsWithStringEncoding, execSync } from 'child_process';
import { ensureDirSync, removeSync, existsSync } from 'fs-extra';
import { dirname, join } from 'path';
import { execSync, ExecSyncOptionsWithStringEncoding } from 'child_process';
import { join, dirname } from 'path';
import { mkdirSync, rmSync } from 'fs';

const LAB_INDICES = Array.from({ length: 22 }, (_, i) => [i + 1]);
// TODO: Update to 22 once all labs are updated/fixed
// const LAB_COUNT = 22;
const LAB_COUNT = 3;
const LABS_TO_TEST = Array.from({ length: LAB_COUNT }, (_, i) => ({
labNumber: i + 1,
}));

describe('nx-react-workshop e2e', () => {
describe('migrations for alternative option', () => {
it('should run the migrations', () => {
createNewWorkspace();
describe('nx-react-workshop', () => {
let projectDirectory: string;

expect(() => checkFilesExist(`node_modules/.bin/nx`)).not.toThrow();
}, 120000);
beforeAll(() => {
projectDirectory = createTestProject();

it.each(LAB_INDICES)(`should complete lab %i`, (i) => {
runNxCommand(
`generate @nrwl/nx-react-workshop:complete-labs --lab=${i} --option=option1`
);
runNxCommand('migrate --run-migrations=migrations.json --verbose');
runNxCommand(
'run-many --target=e2e --parallel=false --exclude=internal-plugin-e2e'
);
runNxCommand('run-many --target=lint --parallel=false');
// The plugin has been built and published to a local registry in the jest globalSetup
// Install the plugin built with the latest source code into the test repo
execSync(`npm install @nrwl/nx-react-workshop@e2e`, {
cwd: projectDirectory,
stdio: 'inherit',
env: process.env,
});
});

describe('migrations for deployment path', () => {
it('should run the migrations', () => {
createNewWorkspace();
afterAll(() => {
// Cleanup the test project
try {
rmSync(projectDirectory, { recursive: true, force: true });
} catch {
// Sometimes the daemon writes to `.nx/` while we're deleting
// Make a second attempt to clean that up
rmSync(projectDirectory, { recursive: true, force: true });
}
});

expect(() => checkFilesExist(`node_modules/.bin/nx`)).not.toThrow();
}, 120000);
it('should be installed', () => {
// npm ls will fail if the package is not installed properly
execSync('npm ls @nrwl/nx-react-workshop', {
cwd: projectDirectory,
stdio: 'inherit',
});
});

describe('migrations', () => {
describe.each(['option1', 'option2'])('for %s', (option) => {
it.each(LABS_TO_TEST)(
`should successfully complete lab $labNumber`,
({ labNumber }) => {
runNxCommand(
`generate @nrwl/nx-react-workshop:complete-labs --lab=${labNumber} --option=${option}`,
projectDirectory
);
runNxCommand(
'migrate --run-migrations=migrations.json --verbose',
projectDirectory
);
runNxCommand(
'run-many --target=e2e --parallel=false --exclude=internal-plugin-e2e',
projectDirectory
);
runNxCommand(
'run-many --target=lint --parallel=false',
projectDirectory
);
}
);
});

it.each(LAB_INDICES)(`should complete lab %i`, (i) => {
it('should support migrating from one version to another', () => {
runNxCommand(
`generate @nrwl/nx-react-workshop:complete-labs --lab=${i} --option=option2`
`generate @nrwl/nx-react-workshop:complete-labs --from=1 --to=${LAB_COUNT}`,
projectDirectory
);
runNxCommand('migrate --run-migrations=migrations.json');
runNxCommand(
'run-many --target=e2e --parallel=false --exclude=internal-plugin-e2e'
'migrate --run-migrations=migrations.json --verbose',
projectDirectory
);
runNxCommand('run-many --target=lint --parallel=false');
runNxCommand(
'run-many --target=e2e --parallel=false --exclude=internal-plugin-e2e',
projectDirectory
);
runNxCommand('run-many --target=lint --parallel=false', projectDirectory);
});

});
});

const scope = `bg-hoard`;
/**
* Creates a test project with create-nx-workspace and installs the plugin
* @returns The directory where the test project was created
*/
function createTestProject() {
const projectName = 'test-project';
const projectDirectory = join(process.cwd(), 'tmp', projectName);

function tmpProjPath() {
return join(process.cwd(), 'tmp', 'nx-e2e', scope);
}
// Ensure projectDirectory is empty
rmSync(projectDirectory, { recursive: true, force: true });
mkdirSync(dirname(projectDirectory), { recursive: true });

function createNewWorkspace() {
const localTmpDir = dirname(tmpProjPath());
ensureDirSync(localTmpDir);
removeSync(tmpProjPath());
// create new workspace
execSync(
`npx create-nx-workspace ${scope} --no-interactive --skip-install --preset=apps --packageManager=npm --ci=skip`,
`npx --yes create-nx-workspace@latest ${projectName} --preset apps --nxCloud=skip --no-interactive`,
{
cwd: localTmpDir,
cwd: dirname(projectDirectory),
stdio: 'inherit',
env: process.env,
}
);
// patch package.json
const path = join(tmpProjPath(), 'package.json');
const json = readJsonFile(path);
json.devDependencies[
'@nrwl/nx-react-workshop'
] = `file:${workspaceRoot}/dist/libs/nx-react-workshop`;
writeJsonFile(path, json);
// install dependencies
execSync('npm install', {
cwd: tmpProjPath(),
stdio: ['ignore', 'ignore', 'ignore'],
});
}
console.log(`Created test project in "${projectDirectory}"`);

function checkFilesExist(...expectedPaths) {
expectedPaths.forEach((path) => {
const filePath = join(tmpProjPath(), path);
if (!existsSync(filePath)) {
throw new Error(`'${filePath}' does not exist`);
}
});
return projectDirectory;
}

function runNxCommand(command): string {
function _runNxCommand(c) {
const execSyncOptions: ExecSyncOptionsWithStringEncoding = {
cwd: tmpProjPath(),
env: process.env,
encoding: 'utf-8',
};
if (existsSync(join(tmpProjPath(), 'package.json'))) {
return execSync(`npx nx ${c}`, execSyncOptions);
} else {
return execSync(`./nx %${c}`, execSyncOptions);
}
}
try {
return _runNxCommand(command)
.toString()
.replace(
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
''
);
} catch (e) {
console.log(e.stdout.toString(), e.stderr.toString());
throw e;
}
function runNxCommand(command: string, projectDirectory: string): string {
const execSyncOptions: ExecSyncOptionsWithStringEncoding = {
cwd: projectDirectory,
env: process.env,
stdio: 'inherit',
encoding: 'utf-8',
};

return execSync(`npx nx ${command}`, execSyncOptions);
}
2 changes: 1 addition & 1 deletion apps/nx-workshop-e2e/tsconfig.spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
"module": "commonjs",
"types": ["jest", "node"]
},
"include": ["**/*.spec.ts", "**/*.d.ts"]
"include": ["jest.config.ts", "**/*.spec.ts", "**/*.d.ts"]
}
10 changes: 0 additions & 10 deletions jest.preset.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,4 @@ const nxPreset = require('@nx/jest/preset').default;

module.exports = {
...nxPreset,
/* TODO: Update to latest Jest snapshotFormat
* By default Nx has kept the older style of Jest Snapshot formats
* to prevent breaking of any existing tests with snapshots.
* It's recommend you update to the latest format.
* You can do this by removing snapshotFormat property
* and running tests with --update-snapshot flag.
* Example: "nx affected --targets=test --update-snapshot"
* More info: https://jestjs.io/docs/upgrading-to-jest29#snapshot-format
*/
snapshotFormat: { escapeString: true, printBasicPrototype: true },
};
16 changes: 8 additions & 8 deletions libs/nx-react-workshop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@
"migrations": "./migrations.json"
},
"dependencies": {
"nx-cloud": "16.0.5",
"nx-cloud": "19.1.0",
"cors": "*",
"node-fetch": "^2.x",
"surge": "*",
"@nx/workspace": "17.0.2",
"@nx/storybook": "17.0.2",
"@nx/plugin": "17.0.2",
"@nx/express": "17.0.2",
"@nx/react": "17.0.2",
"@nx/nest": "17.0.2",
"@nx/next": "17.0.2"
"@nx/workspace": "19.7.2",
"@nx/storybook": "19.7.2",
"@nx/plugin": "19.7.2",
"@nx/express": "19.7.2",
"@nx/react": "19.7.2",
"@nx/nest": "19.7.2",
"@nx/next": "19.7.2"
}
}

This file was deleted.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@
"@nx/workspace": "19.7.2",
"@phenomnomnominal/tsquery": "^4.1.1",
"@storybook/addon-webpack5-compiler-swc": "^1.0.5",
"@swc-node/register": "1.8.0",
"@swc-node/register": "~1.9.1",
"@swc/core": "1.5.7",
"@swc/helpers": "~0.5.11",
"@types/jest": "29.5.12",
"@types/node": "18.19.9",
"@typescript-eslint/eslint-plugin": "7.18.0",
Expand Down
34 changes: 34 additions & 0 deletions tools/scripts/start-local-registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* This script starts a local registry for e2e testing purposes.
* It is meant to be called in jest's globalSetup.
*/
import { startLocalRegistry } from '@nx/js/plugins/jest/local-registry';
import { releasePublish, releaseVersion } from 'nx/release';

export default async () => {
// local registry target to run
const localRegistryTarget = '@nrwl/nx-react-workshop:local-registry';
// storage folder for the local registry
const storage = './dist/local-registry/storage';

global.stopLocalRegistry = await startLocalRegistry({
localRegistryTarget,
storage,
verbose: false,
});

await releaseVersion({
specifier: '0.0.0-e2e',
stageChanges: false,
gitCommit: false,
gitTag: false,
firstRelease: true,
generatorOptionsOverrides: {
skipLockFileUpdate: true,
},
});
await releasePublish({
tag: 'e2e',
firstRelease: true,
});
};
Loading

0 comments on commit 853ee00

Please sign in to comment.