Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore!: re-do graphql schema snapshot testing #911

Merged
merged 2 commits into from
Jan 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
module.exports = {
default(responses) {
maskImageUrl(responses);
return responses;
},
};
const path = require("path");
const {
listFiles,
createExecutor,
} = require("@amazeelabs/graphql-schema-test");

const graphQlConfigPath = path.resolve(__dirname, "../.graphqlconfig");
const queriesPath = path.resolve(__dirname, "queries");

execute = createExecutor(graphQlConfigPath, maskImageUrl);
test.each(listFiles(queriesPath))("%s", async (_, path) => {
await execute(path);
});

// Image URLs contain current date, e.g.
// http://localhost:8888/sites/default/files/2021-01/image.jpg
Expand Down
6 changes: 4 additions & 2 deletions apps/silverback-drupal/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
"scripts": {
"prepare": "if php -v && [[ -z $LAGOON ]]; then composer install && yarn setup && yarn snapshot-create && source .envrc && drush silverback-gatsby:schema-export; fi",
"start": "source .envrc && cd web && php -S 127.0.0.1:8888 .ht.router.php",
"start:silent": "yarn start > /tmp/drupal.log 2>&1",
"login": "source .envrc && drush uli",
"setup": "source .envrc && silverback setup",
"snapshot-create": "source .envrc && silverback snapshot-create test -y",
"snapshot-restore": "source .envrc && silverback snapshot-restore test",
"clear": "source .envrc && drush cr",
"test": "composer install && bash vendor/bin/silverback-test",
"test:integration": "yarn snapshot-restore && start-server-and-test start 8888 test:schema",
"test:schema": "yarn graphql-schema-test generated",
"test:integration": "yarn snapshot-restore && start-server-and-test start:silent 8888 test:schema",
"test:schema": "yarn jest --testMatch '<rootDir>/generated/__tests__/test-queries.js'",
"export-content": "web/modules/custom/silverback_gatsby_test/export_content.sh"
},
"dependencies": {
Expand All @@ -26,6 +27,7 @@
},
"devDependencies": {
"@amazeelabs/graphql-schema-test": "^1.0.4",
"jest": "^27.4.7",
"start-server-and-test": "^1.14.0"
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"test:integration": "yarn lerna run test:integration --stream --concurrency=1 --since",
"test:integration:all": "yarn lerna run test:integration --stream --concurrency=1",
"git-registry": "yarn verdaccio -c config.yml",
"make-local-bins-available-in-monorepo": "rm -rf packages/npm/@amazeelabs/silverback-playwright/dist && mkdir -p packages/npm/@amazeelabs/silverback-playwright/dist/src && echo '' > packages/npm/@amazeelabs/silverback-playwright/dist/src/test-package.js && rm -rf packages/npm/@amazeelabs/graphql-schema-test/dist && mkdir -p packages/npm/@amazeelabs/graphql-schema-test/dist && echo '' > packages/npm/@amazeelabs/graphql-schema-test/dist/graphql-schema-test.js",
"make-local-bins-available-in-monorepo": "rm -rf packages/npm/@amazeelabs/silverback-playwright/dist && mkdir -p packages/npm/@amazeelabs/silverback-playwright/dist/src && echo '' > packages/npm/@amazeelabs/silverback-playwright/dist/src/test-package.js",
"preinstall": "yarn make-local-bins-available-in-monorepo",
"postinstall": "lerna run prepare && husky install && rm -rf node_modules/@-*"
},
Expand Down
36 changes: 22 additions & 14 deletions packages/npm/@amazeelabs/graphql-schema-test/README.md
Original file line number Diff line number Diff line change
@@ -1,35 +1,43 @@
# GraphQL Schema Test

The package takes a set of `.gql` files, runs them against each endpoint defined
in `.graphqlconfig` and creates snapshots containing the responses.
in `.graphqlconfig` and creates snapshots containing the responses. Jest used as
a test runner.

## Usage

Add the package to a project:

```
yarn add --dev @amazeelabs/graphql-schema-test
yarn add --dev @amazeelabs/graphql-schema-test jest
```

Run tests:
Create a Jest test file:

```
yarn graphql-schema-test path/to/directory
```
```js
const {
listFiles,
createExecutor,
} = require('@amazeelabs/graphql-schema-test');

Available flags:
execute = createExecutor('path/to/.graphqlconfig/file', myOptionalSerializer);
test.each(listFiles('path/to/queries/dir'))('%s', async (_, path) => {
await execute(path);
});

- `--verbose` (`-v`)
- `--updateSnapshot` (`-u`)
function myOptionalSerializer(responses) {
// serialize data in responses
}
```

The directory should have the following structure:
Run tests:

- `__tests__`: Directory containing queries in `.gql` files.
- `.graphqlconfig`: GraphQL endpoints definition.
- `serializer.js`: Optional. Serializer for responses.
```
yarn jest --testMatch '<rootDir>/path/to/my/test/file.js'
```

For an example, see
[apps/silverback-drupal/generated](../../../../apps/silverback-drupal/generated).
[apps/silverback-drupal/generated/\_\_tests\_\_](../../../../apps/silverback-drupal/generated/__tests__).

## PhpStorm

Expand Down

This file was deleted.

9 changes: 4 additions & 5 deletions packages/npm/@amazeelabs/graphql-schema-test/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
"description": "Snapshot testing for GraphQL schemas.",
"author": "Amazee Labs",
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"private": false,
"publishConfig": {
"access": "public"
Expand All @@ -16,7 +18,6 @@
},
"dependencies": {
"axios": "^0.24.0",
"jest": "^27",
"jest-specific-snapshot": "^5.0.0",
"lodash": "^4.17.21",
"zx": "^4.2.0"
Expand All @@ -28,19 +29,17 @@
"@types/jest": "^27",
"@types/jest-specific-snapshot": "^0.5.5",
"eslint": "^8",
"jest": "^27",
"prettier": "^2",
"typescript": "^4.5.4"
},
"scripts": {
"prepare": "rm -rf dist && tsc && chmod +x dist/graphql-schema-test.js",
"prepare": "rm -rf dist && tsc",
"precommit": "lint-staged",
"test:static": "tsc --noEmit && eslint \"**/*.{ts,tsx,js,jsx}\" --ignore-path=\"./.gitignore\" --fix",
"test:unit": "jest --passWithNoTests",
"test:integration": "exit 0",
"test:watch": "jest --watch",
"test": "yarn test:static && yarn test:unit && yarn test:integration"
},
"bin": {
"graphql-schema-test": "dist/graphql-schema-test.js"
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,81 +1,76 @@
import axios from 'axios';
import _ from 'lodash';
import { fs, path } from 'zx';
import { fs } from 'zx';

require('jest-specific-snapshot');
const addSerializer = require('jest-specific-snapshot').addSerializer;

const folder = process.env.FOLDER!;
export const listFiles = (
queriesDirPath: string,
): Array<
[
/** Path relative to queriesDirPath. */
string,
/** Absolute path. */
string,
]
> => {
return walk(queriesDirPath).map((fullPath) => [
fullPath.substring(queriesDirPath.length + 1),
fullPath,
]);
};

addSerializer({
serialize(responses: object) {
let processed = processData(responses);
const serializerPath = path.resolve(folder, 'serializer.js');
if (fs.existsSync(serializerPath)) {
const serializer = require(serializerPath).default;
processed = serializer(processed);
}
return JSON.stringify(processed, null, 2);
},
test: () => true,
});

const endpoints: Record<
string,
{ url: string; headers: Record<string, string> }
> = JSON.parse(fs.readFileSync(path.resolve(folder, '.graphqlconfig'), 'utf8'))
.extensions.endpoints;

const dir = path.resolve(folder, '__tests__');
const files = walk(dir).map((fullPath) => [
fullPath.substring(dir.length + 1),
fullPath,
]);

test.each(files)('%s', async (_, path) => {
const results = Object.fromEntries(
await Promise.all(
Object.entries(endpoints).map(async ([name, endpoint]) => {
const res = await axios.post(
endpoint.url,
{ query: fs.readFileSync(path).toString() },
{
headers: endpoint.headers,
validateStatus: null,
},
);
return [
name,
{
code: res.status,
data: res.data,
},
];
}),
),
);
expect(results).toMatchSpecificSnapshot(`${path}.snap`);
});

// Can't use zx.glob because it's async and tests must be defined synchronously.
// Function from https://stackoverflow.com/a/16684530/580371
function walk(dir: string) {
let results: Array<string> = [];
const list = fs.readdirSync(dir);
list.forEach(function (file) {
file = dir + '/' + file;
const stat = fs.statSync(file);
if (stat && stat.isDirectory()) {
results = results.concat(walk(file));
} else {
if (file.endsWith('.gql')) {
// List only .gql files.
results.push(file);
export const createExecutor = (
graphqlConfigPath: string,
serializer?: (responses: object) => object,
): ((queryPath: string) => Promise<void>) => {
addSerializer({
serialize(responses: object) {
const processed = processData(responses);
if (serializer) {
serializer(processed);
}
}
return JSON.stringify(processed, null, 2);
},
test: () => true,
});
return results;
}

const endpoints: Record<
string,
{ url: string; headers: Record<string, string> }
> = JSON.parse(fs.readFileSync(graphqlConfigPath, 'utf8')).extensions
.endpoints;

return async (queryPath: string) => {
const results = Object.fromEntries(
await Promise.all(
Object.entries(endpoints).map(async ([name, endpoint]) => {
const res = await axios.post(
endpoint.url,
{ query: fs.readFileSync(queryPath).toString() },
{
headers: endpoint.headers,
validateStatus: null,
},
);
return [
name,
{
code: res.status,
data: res.data,
},
];
}),
),
);
expect(results).toMatchSpecificSnapshot(
// We can't use `.snap` extension as it conflicts with Jest's default
// snapshots.
`${queryPath}.snapshot`,
);
};
};

function processData(responses: any) {
let processed = responses;
Expand Down Expand Up @@ -136,3 +131,23 @@ function processData(responses: any) {

return processed;
}

// Can't use zx.glob because it's async and tests must be defined synchronously.
// Function from https://stackoverflow.com/a/16684530/580371
function walk(dir: string) {
let results: Array<string> = [];
const list = fs.readdirSync(dir);
list.forEach(function (file) {
file = dir + '/' + file;
const stat = fs.statSync(file);
if (stat && stat.isDirectory()) {
results = results.concat(walk(file));
} else {
if (file.endsWith('.gql')) {
// List only .gql files.
results.push(file);
}
}
});
return results;
}
1 change: 1 addition & 0 deletions packages/npm/@amazeelabs/graphql-schema-test/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": false,
"jsx": "react",
"declaration": true,
"outDir": "dist"
},
"exclude": [
Expand Down