Fixtures and CI

Fixtures, Test Isolation, and CI Pipelines

Reuse the factories of Sample Data as fixtures: aBook() creates an author and a book, aReview() a book, a user and a review, each taking an overrides object so a test states only the field it is about. Tests that build their own data survive seed changes.

Isolation is the harder half. Clearing every collection in beforeEach, as in mongodb-memory-server, is the default answer and costs a few milliseconds. The alternative that scales is one database per process: node:test runs test files in parallel child processes, so naming the database after process.pid stops two files colliding, whether they share a server or start their own.

test/db.js — inside startDatabase(): one database per test processJavaScript
const dbName = `bookshelf_test_${process.pid}`;
const uri = process.env.MONGO_URI                  // CI or a local server, shared by all files
  ?? (mongod = await MongoMemoryServer.create()).getUri();
await mongoose.connect(uri, { dbName });

Run two such files with node --test test/books.test.js test/reviews.test.js against one server and they report bookshelf_test_69108 and bookshelf_test_72012: 6 tests, 6 passed, 1131 ms. With a memory server each they took 1604 ms, so wherever a MongoDB 1,815 is already running — a developer's machine, a CI service container — pointing the suite at it saves the per-file start. Call dropDatabase() in after so the server does not fill up with bookshelf_test_*.

.github/workflows/test.yml — a MongoDB service containerYAML
    services:
      mongo: { image: 'mongo:8.3', ports: ['27017:27017'] }
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
      - run: npm ci && npm test
        env: { MONGO_URI: 'mongodb://127.0.0.1:27017/' }

A service container starts as a standalone, so a suite needing transactions keeps MongoMemoryReplSet or Testcontainers 328,662 on CI. Run the migrations in the pipeline too: migrate-mongo 1,030 up against a database restored from a production dump is the only honest rehearsal of the deploy.