test method

  1. @override
String test(
  1. String path,
  2. String sourcePath,
  3. String baseName,
  4. String className,
)
override

Define test code. The path path is passed relative to lib, sourcePath is the source file path, baseName is the filename, and className is the filename converted to Pascal case.

テストコードを定義します。pathlibからの相対パス、sourcePathにソースファイルのパス、baseNameにファイル名が渡され、classNameにファイル名をパスカルケースに変換した値が渡されます。

Implementation

@override
String test(
    String path, String sourcePath, String baseName, String className) {
  return """
/**
 * Test for ${className.toPascalCase()} functions.
 */
import {
describe,
expect,
it,
beforeAll,
afterAll,
afterEach,
} from '@jest/globals';
import * as admin from 'firebase-admin';

/**
 * File path of Functions for testing (omit extensions).
 */
import { ${className.toPascalCase()}FirestoreTriggered } from '../src/functions/$baseName';

/**
 * Firebase project ID for testing.
 */
const testProjectId = "\${testProjectId}";

/**
 * Regions to deploy Functions.
 */
const regions = ["us-central1"];

// Create tests for Functions.
const tester = require("firebase-functions-test")({
projectId: testProjectId,
});
describe(`Test: ${className.toPascalCase()}FirestoreTriggerred`, () => {
let functions: any;

// Performs initial setup for testing.
beforeAll(() => {
  admin.initializeApp();
  process.env.FIRESTORE_EMULATOR_HOST = "127.0.0.1:8080";
  functions = new ${className.toPascalCase()}FirestoreTriggered().build(regions);
});
afterEach(async () => {
  await fetch(
    `http://\${process.env.FIRESTORE_EMULATOR_HOST}/emulator/v1/projects/\${testProjectId}/databases/(default)/documents`,
    { method: "DELETE" },
  );
});
afterAll(() => {
  tester.cleanup()
})

// The actual test is written from here.
it("Test Item 1", async () => {
  const firestoreInstance = admin.firestore();
  const path = "collection/documentId";
  const beforeData: { [key: string]: any } = {
  };
  const afterData: { [key: string]: any } = {
  };
  await firestoreInstance.doc(path).set(
    beforeData, { merge: true },
  );

  const beforeSnap = tester.firestore.makeDocumentSnapshot(
    beforeData, path,
  );

  const afterSnap = tester.firestore.makeDocumentSnapshot(
    afterData, path,
  );
  const change = await tester.makeChange(
    beforeSnap,
    afterSnap,
  );

  const functionsWrapped = tester.wrap(functions);
  await functionsWrapped({
    data: change,
    params: parameters,
  });
});
});
""";
}