Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/ship-pr

Progressive ship-pr loop for agents: PR status, Bugbot, review sort, human review feedback, 7-day decisions, merge, deploy, wrap-up.

FollowFork

Files

emit-report.test.ts

48 lines · 2.5 KB · TypeScript
import assert from "node:assert/strict";
import { registerHooks } from "node:module";
import { test } from "node:test";

registerHooks({
	resolve: (specifier, context, next) => (specifier === "kody:runtime" ? { url: "data:text/javascript,export const events = null", shortCircuit: true } : next(specifier, context)),
});
const { emitReportPosted, REPORT_POSTED_TOPIC } = await import("./emit-report.ts");

const payload = { prUrl: "https://github.com/o/r/pull/1", outcome: "shipped", summary: "Merged." };

function runtime(opts: { hook?: { ok: boolean; status: number } | "unmapped" } = {}) {
	const events: Array<{ topic: string; idempotencyKey: string; payload: Record<string, unknown> }> = [];
	const posts: Array<{ url: string; init: { headers: Record<string, string>; body: string } }> = [];
	return {
		events,
		posts,
		rt: {
			events: { dispatch: async (e: (typeof events)[number]) => void events.push(e) },
			credential: async () => {
				if (!opts.hook || opts.hook === "unmapped") throw new Error("credential not mapped");
				return { fetch: async (url: string, init: never) => (posts.push({ url, init }), opts.hook as { ok: boolean; status: number }) };
			},
		},
	};
}

test("a report goes out one way: the webhook credential when mapped, else the same-org event, and a dry run sends nothing", async () => {
	const event = runtime({ hook: "unmapped" });
	assert.deepEqual(await emitReportPosted("report:k:Shipped", payload, false, event.rt), { emitted: true, via: "event" });
	assert.equal(event.events[0]!.topic, REPORT_POSTED_TOPIC);
	assert.equal(event.events[0]!.idempotencyKey, "report:k:Shipped");

	const hook = runtime({ hook: { ok: true, status: 200 } });
	assert.deepEqual(await emitReportPosted("report:k:Shipped", payload, false, hook.rt), { emitted: true, via: "webhook" });
	assert.equal(hook.events.length, 0, "never both transports");
	assert.equal(hook.posts[0]!.init.headers["Idempotency-Key"], "report:k:Shipped");
	assert.equal(JSON.parse(hook.posts[0]!.init.body).prUrl, payload.prUrl);

	const refused = runtime({ hook: { ok: false, status: 409 } });
	const failed = await emitReportPosted("k", payload, false, refused.rt);
	assert.equal(failed.emitted, false);
	assert.match(String((failed as { error?: string }).error), /HTTP 409/);
	assert.equal(refused.events.length, 0, "a refused webhook does not fall back to the event");

	assert.deepEqual(await emitReportPosted("k", payload, true, hook.rt), { emitted: false, skipped: "dryRun" });
	assert.equal(hook.posts.length, 1);
});