All skills
bmad-labs avatar

/typescript-e2e-testing

@3bcc7a6
by bmad-labsbmad-labs/skills15 stars
4

E2E and integration testing for TypeScript/NestJS projects using Jest, supertest, and real infrastructure via Docker (Kafka, PostgreSQL, MongoDB, Redis) with the Given-When-Then pattern. Use whenever the user is working on `.e2e-spec.ts` files or anything under `test/e2e/`, or asks to set up, write, review, run, debug, or optimize E2E or integration tests — including flaky tests, docker-compose for tests, Kafka/Redpanda consumers, test isolation, or GWT compliance.

Use this Skill: https://skilld.dev/gh/bmad-labs/skills/typescript-e2e-testing

This session only. Nothing lands on disk.

referencesmongodbtest-helper.md

≈1.1k tokens on demand. Your agent reads this file only when SKILL.md points to it.

MongoDB Test Helper

Complete Implementation

// test/helpers/mongodb.helper.ts
import { Connection, Model, Document } from 'mongoose';

export class MongoDbTestHelper {
  constructor(private connection: Connection) {}

  /**
   * Clear all collections
   */
  async clearAllCollections(): Promise<void> {
    const collections = Object.keys(this.connection.collections);
    for (const collectionName of collections) {
      const collection = this.connection.collections[collectionName];
      await collection.deleteMany({});
    }
  }

  /**
   * Clear specific collections
   */
  async clearCollections(collectionNames: string[]): Promise<void> {
    for (const name of collectionNames) {
      const collection = this.connection.collections[name];
      if (collection) {
        await collection.deleteMany({});
      }
    }
  }

  /**
   * Drop entire database
   */
  async dropDatabase(): Promise<void> {
    await this.connection.dropDatabase();
  }

  /**
   * Get model by name
   */
  getModel<T>(name: string): Model<T> {
    return this.connection.model<T>(name);
  }

  /**
   * Assert document exists with expected values
   */
  async assertDocumentExists(
    model: Model<any>,
    query: object,
    expected?: object
  ): Promise<void> {
    const doc = await model.findOne(query).lean().exec();
    expect(doc).toBeDefined();
    expect(doc).not.toBeNull();
    if (expected) {
      expect(doc).toMatchObject(expected);
    }
  }

  /**
   * Assert document does not exist
   */
  async assertDocumentNotExists(
    model: Model<any>,
    query: object
  ): Promise<void> {
    const doc = await model.findOne(query).exec();
    expect(doc).toBeNull();
  }

  /**
   * Assert document count
   */
  async assertDocumentCount(
    model: Model<any>,
    query: object,
    expectedCount: number
  ): Promise<void> {
    const count = await model.countDocuments(query).exec();
    expect(count).toBe(expectedCount);
  }

  /**
   * Seed documents for testing
   */
  async seedDocuments<T>(model: Model<T>, documents: Partial<T>[]): Promise<T[]> {
    return model.insertMany(documents) as unknown as T[];
  }

  /**
   * Create indexes for test collections
   */
  async ensureIndexes(): Promise<void> {
    const models = this.connection.modelNames();
    for (const modelName of models) {
      const model = this.connection.model(modelName);
      await model.ensureIndexes();
    }
  }
}

Usage Example

describe('Product API E2E', () => {
  let helper: MongoDbTestHelper;
  let productModel: Model<Product>;
  let categoryModel: Model<Category>;

  beforeAll(async () => {
    const setup = await createTestApp([ProductModule]);
    helper = new MongoDbTestHelper(setup.app.get(getConnectionToken()));
    productModel = helper.getModel<Product>('Product');
    categoryModel = helper.getModel<Category>('Category');
  });

  beforeEach(async () => {
    // Wait for in-flight operations
    await new Promise(r => setTimeout(r, 500));
    await helper.clearCollections(['products', 'categories']);
  });

  afterAll(async () => {
    await app.close();
  });

  it('should create product', async () => {
    // GIVEN: Category exists
    const category = await categoryModel.create({ name: 'Electronics' });

    // WHEN: Creating product
    const response = await request(httpServer)
      .post('/products')
      .send({
        name: 'Laptop',
        categoryId: category._id.toString(),
        price: 999.99,
      })
      .expect(201);

    // THEN: Product persisted
    await helper.assertDocumentExists(
      productModel,
      { name: 'Laptop' },
      { categoryId: category._id, price: 999.99 }
    );
  });
});

API Reference

Method Description
clearAllCollections() Delete all documents from all collections
clearCollections(names) Delete documents from specified collections
dropDatabase() Drop the entire test database
getModel(name) Get Mongoose model by name
assertDocumentExists(model, query, expected) Assert document exists with values
assertDocumentNotExists(model, query) Assert document does not exist
assertDocumentCount(model, query, count) Assert document count
seedDocuments(model, docs) Insert test documents
ensureIndexes() Ensure indexes on all models

Source: SKILL.md on GitHub

1 alert16d5 checks · Risk SAFE
  • Gen Agent Trust Hub16d

    This skill provides comprehensive workflows and reference materials for E2E testing in TypeScript/NestJS projects. It uses standard development tools like Jest, Docker, and shell commands. No malicious patterns or security risks were detected.

  • Socket16d

    No alerts

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer7mo

    30/103 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 3bcc7a6. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 days ago.

Activeupdated 5 months ago
  • TypeScript
  • jest
  • nestjs
  • e2e-testing
  • supertest
  • docker
  • kafka
  • postgres
  • mongodb
  • redis
  • integration-testing
  • gwt-pattern

README badge

README badge for bmad-labs/skills

Writes E2E and integration tests for NestJS projects using Jest and supertest against real Docker infrastructure (Kafka, PostgreSQL, MongoDB, Redis) following the Given-When-Then pattern. Covers test setup, writing, review, debugging, and optimization workflows with technology-specific helpers and isolation strategies for each service.

Generated from the current SKILL.md.

Does this skill work with NestJS only?
The skill is built for NestJS projects using Jest and supertest, but the patterns and workflows apply to any TypeScript backend with HTTP endpoints. Technology-specific helpers exist for Kafka, PostgreSQL, MongoDB, and Redis.
Do I need Docker running to use this skill?
Yes. The skill assumes real infrastructure via Docker (Kafka, PostgreSQL, MongoDB, Redis). Tests execute against actual services, not mocks.
What if my E2E tests are flaky or failing?
The Debugging E2E Test workflow provides a systematic protocol: fix one test at a time using isolated test runs, verify with 3-5 consecutive runs before moving to the next failure, then run the full suite only once all tests pass individually.
Does this skill cover GraphQL or gRPC testing?
Yes. The API testing reference includes examples for REST, GraphQL, and gRPC, plus external API mocking with MSW and Nock.
What is the Given-When-Then pattern and is it mandatory?
GWT is the mandatory test structure: Given describes setup state, When describes the action under test, Then describes expected outcomes. All E2E tests in this skill must follow this pattern.

Generated from the current SKILL.md. These answers refresh after source changes.