Skip to content

Neo4j Fixture ​

The neo4jClient fixture provides a Neo4j graph database client for running Cypher reads, writes and transactions. It uses the official neo4j-driver and returns plain JS objects, with Neo4j Integers converted to numbers.


What It Does ​

  • Connects to Neo4j over bolt:// or neo4j:// and verifies connectivity on setup
  • Runs read queries (run) with READ routing and returns each record as a plain object
  • Runs write queries (write) with WRITE routing and returns update counters
  • Runs several statements atomically with executeInTransaction
  • Converts Neo4j Integers to JS numbers, and nodes/relationships/paths to plain objects
  • Closes the driver on teardown

Setup ​

Install ​

The driver is an optional peer dependency. Install it in your project:

bash
npm install --save-dev neo4j-driver

Run it in a container ​

No Neo4j server to connect to? Set PW_NEO4J_CONTAINER=true (or container: true in config) and the fixture starts one with Testcontainers for the run, then removes it. Needs Docker and npm install --save-dev testcontainers. See Testcontainers.

Environment Variables ​

VariableRequiredDescription
PW_NEO4J_URIYesConnection URI, e.g. bolt://localhost:7687
PW_NEO4J_USERNAMEYesAuthentication username
PW_NEO4J_PASSWORDYesAuthentication password
PW_NEO4J_DATABASENoTarget database (default: the server's default database)

Configuration via environments.json ​

json
{
  "environments": {
    "local": {
      "neo4j": {
        "uri": "bolt://localhost:7687",
        "username": "neo4j",
        "password": "testpassword",
        "database": "neo4j",
        "connectionTimeout": 10000
      }
    }
  }
}

Configuration via playwright.config.ts ​

typescript
import { defineConfig } from '@playwright/test';
import type { ConfigOptions } from '@inluxc/propmaster';

export default defineConfig<ConfigOptions>({
  projects: [
    {
      name: 'graph',
      testMatch: '**/graph/**/*.spec.ts',
      use: {
        neo4j: {
          uri: 'bolt://localhost:7687',
          username: 'neo4j',
          password: process.env.NEO4J_PASSWORD!,
        },
      },
    },
  ],
});

Configuration Options ​

OptionTypeDefaultDescription
uristring—bolt:// (single server) or neo4j:// (routing/cluster) URI
usernamestring—Authentication username
passwordstring—Authentication password
databasestringserver defaultDatabase to run queries against
connectionTimeoutnumber10000Connection and acquisition timeout in ms

Local Server ​

bash
docker run -p 7687:7687 -e NEO4J_AUTH=neo4j/testpassword neo4j:5

Usage ​

typescript
import { test, expect } from '@inluxc/propmaster';

test('create and query a relationship', async ({ neo4jClient }) => {
  const counters = await neo4jClient.write(
    'CREATE (:Person {name: $a})-[:KNOWS]->(:Person {name: $b})',
    { a: 'Alice', b: 'Bob' },
  );
  expect(counters.relationshipsCreated).toBe(1);

  const rows = await neo4jClient.run<{ friend: string }>(
    'MATCH (:Person {name: $name})-[:KNOWS]->(f) RETURN f.name AS friend',
    { name: 'Alice' },
  );
  expect(rows).toEqual([{ friend: 'Bob' }]);
});

test('write atomically', async ({ neo4jClient }) => {
  await neo4jClient.executeInTransaction(async (tx) => {
    await tx.run('CREATE (:Order {id: $id})', { id: 'ORD-1' });
    await tx.run('MATCH (o:Order {id: $id}) CREATE (o)-[:CONTAINS]->(:Item {sku: $sku})', { id: 'ORD-1', sku: 'A' });
  }); // committed when the callback resolves, rolled back if it throws
});

Always pass values as parameters ($name) rather than interpolating them into the Cypher string.

API Reference ​

MethodReturnsDescription
run<T>(cypher, params?)Promise<T[]>Read query; each record via record.toObject(), Integers as numbers
write(cypher, params?)Promise<Neo4jWriteResult>Write query; returns nodesCreated, relationshipsCreated, propertiesSet, nodesDeleted, relationshipsDeleted
executeInTransaction(fn)Promise<R>Runs fn(tx) in one write transaction; tx.run<T>(cypher, params?) returns T[]
close()Promise<void>Closes the driver (done automatically on teardown)

Test Data Isolation ​

Neo4j has no key prefix equivalent, so tag every node your test creates with a runId property. A write with a runId parameter is cleaned up automatically: when the test ends, pass or fail, every node with that runId is detach-deleted. Use the test's own run ID:

typescript
test('...', async ({ neo4jClient, testData }) => {
  await neo4jClient.write('CREATE (:Person {runId: $runId, name: $name})', { runId: testData.runId, name: 'Alice' });
  // after the test: MATCH (n {runId: $runId}) DETACH DELETE n
});

Writes in executeInTransaction are tracked once the transaction commits. Pass { keep: true } as the third argument of write to leave the nodes in place. A runId shared by a whole file is deleted when the first test ends. See Test Data and Automatic Cleanup.


Lifecycle ​

  1. Setup — creates the driver and calls driver.verifyConnectivity()
  2. Use — the test receives the neo4jClient
  3. Teardown — closes the driver

Error Handling ​

ErrorWhen
FixtureInitError('neo4j', 'connect', …)Server unreachable, bad credentials, or missing config. Includes uri, database, timeout and the driver's reason
FixtureOperationError('neo4j', 'run' | 'write' | 'transaction', …)A Cypher statement or transaction failed. Includes the cypher statement and reason

Released under the MIT License.