feat(features): contract suites for all repository interfaces
Each repository interface now has a contract suite under
src/__contracts__/. Both Mock and Payload implementations run the
same suite, eliminating mock-vs-real drift. Payload impls back the
contract with an in-memory stub via vi.mock('payload') + a small
buildPayloadStub helper.
Spec: §5.2, §6.4
This commit is contained in:
120
packages/blog/src/__contracts__/articles-repository.contract.ts
Normal file
120
packages/blog/src/__contracts__/articles-repository.contract.ts
Normal file
@@ -0,0 +1,120 @@
|
||||
import { it, expect, beforeEach } from "vitest";
|
||||
import { defineContractSuite } from "@repo/core-testing/contract";
|
||||
import type { IArticlesRepository } from "../application/repositories/articles-repository.interface.js";
|
||||
import { articleFactory } from "../__factories__/article.factory.js";
|
||||
|
||||
export const articlesRepositoryContract =
|
||||
defineContractSuite<IArticlesRepository>(
|
||||
"IArticlesRepository",
|
||||
({ buildSubject }) => {
|
||||
let repo: IArticlesRepository;
|
||||
|
||||
beforeEach(async () => {
|
||||
articleFactory.reset();
|
||||
repo = await buildSubject();
|
||||
});
|
||||
|
||||
// --- createArticle ---
|
||||
|
||||
it("createArticle returns an article with an id and the correct fields", async () => {
|
||||
const seed = articleFactory.build({ title: "Hello World" });
|
||||
const created = await repo.createArticle(seed);
|
||||
// Implementations may assign their own id (e.g. Payload), so we only
|
||||
// verify the id is a non-empty string and the other fields match.
|
||||
expect(typeof created.id).toBe("string");
|
||||
expect(created.id.length).toBeGreaterThan(0);
|
||||
expect(created.title).toBe("Hello World");
|
||||
expect(created.slug).toBe(seed.slug);
|
||||
expect(created.status).toBe(seed.status);
|
||||
expect(created.authorId).toBe(seed.authorId);
|
||||
});
|
||||
|
||||
// --- getArticle ---
|
||||
|
||||
it("createArticle then getArticle returns it by the returned id", async () => {
|
||||
const seed = articleFactory.build();
|
||||
const created = await repo.createArticle(seed);
|
||||
// Use the id returned by createArticle (Payload may differ from seed.id)
|
||||
const result = await repo.getArticle(created.id);
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.id).toBe(created.id);
|
||||
expect(result?.slug).toBe(seed.slug);
|
||||
});
|
||||
|
||||
it("getArticle returns undefined for missing id", async () => {
|
||||
expect(await repo.getArticle("does-not-exist")).toBeUndefined();
|
||||
});
|
||||
|
||||
// --- getArticleBySlug ---
|
||||
|
||||
it("createArticle then getArticleBySlug returns it by slug", async () => {
|
||||
const seed = articleFactory.build({ slug: "my-slug" });
|
||||
const created = await repo.createArticle(seed);
|
||||
const result = await repo.getArticleBySlug("my-slug");
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.id).toBe(created.id);
|
||||
expect(result?.slug).toBe("my-slug");
|
||||
});
|
||||
|
||||
it("getArticleBySlug returns undefined for missing slug", async () => {
|
||||
expect(await repo.getArticleBySlug("does-not-exist")).toBeUndefined();
|
||||
});
|
||||
|
||||
// --- getArticles ---
|
||||
|
||||
it("getArticles returns empty array when no articles", async () => {
|
||||
const list = await repo.getArticles();
|
||||
expect(list).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("getArticles returns all articles when no filter", async () => {
|
||||
await repo.createArticle(articleFactory.build());
|
||||
await repo.createArticle(articleFactory.build());
|
||||
const list = await repo.getArticles();
|
||||
expect(list).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("getArticles filters by status", async () => {
|
||||
await repo.createArticle(articleFactory.build({ status: "draft" }));
|
||||
await repo.createArticle(
|
||||
articleFactory.build({ status: "published" }),
|
||||
);
|
||||
const drafts = await repo.getArticles({ status: "draft" });
|
||||
expect(drafts).toHaveLength(1);
|
||||
expect(drafts[0]?.status).toBe("draft");
|
||||
});
|
||||
|
||||
it("getArticles filters by authorId", async () => {
|
||||
await repo.createArticle(
|
||||
articleFactory.build({ authorId: "author-a" }),
|
||||
);
|
||||
await repo.createArticle(
|
||||
articleFactory.build({ authorId: "author-b" }),
|
||||
);
|
||||
const result = await repo.getArticles({ authorId: "author-a" });
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]?.authorId).toBe("author-a");
|
||||
});
|
||||
|
||||
// --- updateArticle ---
|
||||
|
||||
it("updateArticle changes fields and returns updated article", async () => {
|
||||
const seed = articleFactory.build({ status: "draft" });
|
||||
const created = await repo.createArticle(seed);
|
||||
// Use the returned id for the update lookup
|
||||
const updated = await repo.updateArticle(created.id, {
|
||||
status: "published",
|
||||
});
|
||||
expect(updated).toBeDefined();
|
||||
expect(updated?.id).toBe(created.id);
|
||||
expect(updated?.status).toBe("published");
|
||||
});
|
||||
|
||||
it("updateArticle returns undefined for missing id", async () => {
|
||||
const result = await repo.updateArticle("no-such-id", {
|
||||
title: "new",
|
||||
});
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
import { describe } from "vitest";
|
||||
import { MockArticlesRepository } from "@/infrastructure/repositories/mock-articles.repository";
|
||||
import { articlesRepositoryContract } from "@/__contracts__/articles-repository.contract";
|
||||
|
||||
describe("MockArticlesRepository", () => {
|
||||
articlesRepositoryContract.run(() => new MockArticlesRepository());
|
||||
});
|
||||
@@ -1,57 +1,165 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { PayloadArticlesRepository } from "./payload-articles.repository";
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
import { PayloadArticlesRepository } from "@/infrastructure/repositories/payload-articles.repository";
|
||||
import { articlesRepositoryContract } from "@/__contracts__/articles-repository.contract";
|
||||
import { stubPayloadConfig } from "@repo/core-testing/payload/stub-config";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// In-memory Payload stub used by both the contract suite and impl-specific tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildPayloadStub() {
|
||||
const store = new Map<string, Record<string, unknown>>();
|
||||
|
||||
return {
|
||||
create: vi.fn(
|
||||
async ({
|
||||
data,
|
||||
}: {
|
||||
collection: string;
|
||||
data: Record<string, unknown>;
|
||||
overrideAccess?: boolean;
|
||||
}) => {
|
||||
// Payload assigns an id; here we require the data to carry one
|
||||
// (the repository passes `id` via the mapped domain object implicitly
|
||||
// through the Article — we expose the mapped doc back from createArticle).
|
||||
// The stub returns the data as-is so the mapDoc function can work.
|
||||
const doc = { id: `stub-${store.size + 1}`, ...data };
|
||||
store.set(String(doc.id), doc);
|
||||
return doc;
|
||||
},
|
||||
),
|
||||
find: vi.fn(
|
||||
async ({
|
||||
where,
|
||||
limit,
|
||||
}: {
|
||||
collection: string;
|
||||
where?: {
|
||||
slug?: { equals: string };
|
||||
status?: { equals: string };
|
||||
author?: { equals: string };
|
||||
};
|
||||
limit?: number;
|
||||
page?: number;
|
||||
overrideAccess?: boolean;
|
||||
}) => {
|
||||
let docs = Array.from(store.values());
|
||||
if (where?.slug) {
|
||||
docs = docs.filter((d) => d.slug === where.slug?.equals);
|
||||
}
|
||||
if (where?.status) {
|
||||
docs = docs.filter((d) => d.status === where.status?.equals);
|
||||
}
|
||||
if (where?.author) {
|
||||
docs = docs.filter((d) => d.author === where.author?.equals);
|
||||
}
|
||||
if (limit !== undefined) {
|
||||
docs = docs.slice(0, limit);
|
||||
}
|
||||
return { docs };
|
||||
},
|
||||
),
|
||||
findByID: vi.fn(
|
||||
async ({ id }: { collection: string; id: string; overrideAccess?: boolean }) => {
|
||||
const doc = store.get(String(id));
|
||||
if (!doc) throw new Error(`Not found: ${id}`);
|
||||
return doc;
|
||||
},
|
||||
),
|
||||
update: vi.fn(
|
||||
async ({
|
||||
id,
|
||||
data,
|
||||
}: {
|
||||
collection: string;
|
||||
id: string;
|
||||
data: Record<string, unknown>;
|
||||
overrideAccess?: boolean;
|
||||
}) => {
|
||||
const existing = store.get(String(id));
|
||||
if (!existing) throw new Error(`Not found: ${id}`);
|
||||
const updated = { ...existing, ...data };
|
||||
store.set(String(id), updated);
|
||||
return updated;
|
||||
},
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
vi.mock("payload", () => ({
|
||||
getPayload: vi.fn(),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Contract suite
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("PayloadArticlesRepository", () => {
|
||||
const mockConfig = {} as never;
|
||||
|
||||
it("maps a Payload doc to a domain Article on getArticleBySlug", async () => {
|
||||
const { getPayload } = await import("payload");
|
||||
const findMock = vi.fn().mockResolvedValue({
|
||||
docs: [
|
||||
{
|
||||
id: "p-123",
|
||||
title: "Hello",
|
||||
slug: "hello",
|
||||
content: { type: "doc", children: [] },
|
||||
status: "published",
|
||||
author: "u1",
|
||||
createdAt: "2026-05-04T12:00:00.000Z",
|
||||
updatedAt: "2026-05-04T12:00:00.000Z",
|
||||
},
|
||||
],
|
||||
describe("contract", () => {
|
||||
articlesRepositoryContract.run(async () => {
|
||||
const stub = buildPayloadStub();
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue(stub);
|
||||
return new PayloadArticlesRepository(stubPayloadConfig);
|
||||
});
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
find: findMock,
|
||||
});
|
||||
|
||||
const repo = new PayloadArticlesRepository(mockConfig);
|
||||
const result = await repo.getArticleBySlug("hello");
|
||||
|
||||
expect(findMock).toHaveBeenCalledWith({
|
||||
collection: "articles",
|
||||
where: { slug: { equals: "hello" } },
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(result?.id).toBe("p-123");
|
||||
expect(result?.slug).toBe("hello");
|
||||
expect(result?.status).toBe("published");
|
||||
expect(result?.authorId).toBe("u1");
|
||||
expect(result?.createdAt).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it("returns undefined when slug is not found", async () => {
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
find: vi.fn().mockResolvedValue({ docs: [] }),
|
||||
// -------------------------------------------------------------------------
|
||||
// Impl-specific tests: Payload doc → domain mapping
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
describe("Payload doc → domain mapping", () => {
|
||||
const mockConfig = {} as never;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const repo = new PayloadArticlesRepository(mockConfig);
|
||||
const result = await repo.getArticleBySlug("missing");
|
||||
expect(result).toBeUndefined();
|
||||
it("maps a Payload doc to a domain Article on getArticleBySlug", async () => {
|
||||
const { getPayload } = await import("payload");
|
||||
const findMock = vi.fn().mockResolvedValue({
|
||||
docs: [
|
||||
{
|
||||
id: "p-123",
|
||||
title: "Hello",
|
||||
slug: "hello",
|
||||
content: { type: "doc", children: [] },
|
||||
status: "published",
|
||||
author: "u1",
|
||||
createdAt: "2026-05-04T12:00:00.000Z",
|
||||
updatedAt: "2026-05-04T12:00:00.000Z",
|
||||
},
|
||||
],
|
||||
});
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
find: findMock,
|
||||
});
|
||||
|
||||
const repo = new PayloadArticlesRepository(mockConfig);
|
||||
const result = await repo.getArticleBySlug("hello");
|
||||
|
||||
expect(findMock).toHaveBeenCalledWith({
|
||||
collection: "articles",
|
||||
where: { slug: { equals: "hello" } },
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(result?.id).toBe("p-123");
|
||||
expect(result?.slug).toBe("hello");
|
||||
expect(result?.status).toBe("published");
|
||||
expect(result?.authorId).toBe("u1");
|
||||
expect(result?.createdAt).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it("returns undefined when slug is not found", async () => {
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
find: vi.fn().mockResolvedValue({ docs: [] }),
|
||||
});
|
||||
|
||||
const repo = new PayloadArticlesRepository(mockConfig);
|
||||
const result = await repo.getArticleBySlug("missing");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user