@yaebal/test 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.test.ts CHANGED
@@ -1,13 +1,30 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import { Composer, Context } from "@yaebal/core";
3
+ import { Composer, Context, TelegramError } from "@yaebal/core";
4
4
  import {
5
+ callbackContext,
5
6
  callbackUpdate,
7
+ channelPostUpdate,
8
+ chatJoinRequestUpdate,
9
+ chatMemberUpdate,
10
+ chosenInlineResultUpdate,
11
+ collectUpdates,
6
12
  createContext,
7
13
  createUpdate,
14
+ editedMessageUpdate,
15
+ findButton,
16
+ inlineQueryUpdate,
17
+ messageContext,
8
18
  messageUpdate,
9
19
  mockApi,
20
+ myChatMemberUpdate,
21
+ pollAnswerUpdate,
22
+ pollUpdate,
23
+ preCheckoutQueryUpdate,
10
24
  runMiddleware,
25
+ shippingQueryUpdate,
26
+ webhookRequest,
27
+ withFetch,
11
28
  } from "./index.js";
12
29
 
13
30
  test("mockApi records calls and resolves sensible defaults", async () => {
@@ -99,3 +116,205 @@ test("a handler calling ctx.reply records a sendMessage call", async () => {
99
116
 
100
117
  assert.deepEqual(call?.params?.reply_parameters, { message_id: 1 });
101
118
  });
119
+
120
+ test("mockApi auto-increments message_id across send* calls", async () => {
121
+ const { api } = mockApi();
122
+
123
+ const first = await api.sendMessage({ chat_id: 1, text: "a" });
124
+ const second = await api.sendMessage({ chat_id: 1, text: "b" });
125
+
126
+ assert.deepEqual(first, { message_id: 1 });
127
+ assert.deepEqual(second, { message_id: 2 });
128
+ });
129
+
130
+ test("mockApi results: static override replaces the built-in default", async () => {
131
+ const { api } = mockApi({ results: { sendMessage: { message_id: 99 } } });
132
+
133
+ assert.deepEqual(await api.sendMessage({ chat_id: 1 }), { message_id: 99 });
134
+ });
135
+
136
+ test("mockApi results: an Error value makes the call throw", async () => {
137
+ const { api } = mockApi({
138
+ results: { sendMessage: new TelegramError("sendMessage", 400, "Bad Request") },
139
+ });
140
+
141
+ await assert.rejects(api.sendMessage({ chat_id: 1 }), TelegramError);
142
+ });
143
+
144
+ test("mockApi results: a function sees params and a running attempt count", async () => {
145
+ const { api } = mockApi({
146
+ results: {
147
+ sendMessage: (params: Record<string, unknown> | undefined, attempt: number) =>
148
+ attempt <= 2
149
+ ? new TelegramError("sendMessage", 429, "retry after 0")
150
+ : { message_id: 1, echo: params?.text },
151
+ },
152
+ });
153
+
154
+ api.onError((_m, _e, attempt) => (attempt <= 2 ? { retry: true } : undefined));
155
+
156
+ const result = await api.sendMessage({ chat_id: 1, text: "hi" });
157
+ assert.deepEqual(result, { message_id: 1, echo: "hi" });
158
+ });
159
+
160
+ test("mockApi.setResult overrides after creation; reset() clears calls and counters", async () => {
161
+ const { api, calls, setResult, reset } = mockApi();
162
+
163
+ await api.sendMessage({ chat_id: 1 });
164
+ setResult("sendMessage", { message_id: 42 });
165
+ assert.deepEqual(await api.sendMessage({ chat_id: 1 }), { message_id: 42 });
166
+ assert.equal(calls.length, 2);
167
+
168
+ reset();
169
+ assert.equal(calls.length, 0);
170
+ assert.deepEqual(await api.sendMessage({ chat_id: 1 }), { message_id: 42 });
171
+ });
172
+
173
+ test("mockApi.lastCall and callsTo filter recorded calls", async () => {
174
+ const { api, lastCall, callsTo } = mockApi();
175
+
176
+ await api.sendMessage({ chat_id: 1, text: "a" });
177
+ await api.answerCallbackQuery({ callback_query_id: "1" });
178
+ await api.sendMessage({ chat_id: 1, text: "b" });
179
+
180
+ assert.equal(lastCall()?.method, "sendMessage");
181
+ assert.equal(lastCall("answerCallbackQuery")?.method, "answerCallbackQuery");
182
+ assert.equal(lastCall("sendMessage")?.params?.text, "b");
183
+ assert.equal(callsTo("sendMessage").length, 2);
184
+ });
185
+
186
+ test("mockApi hooks actually run: before rewrites params, after rewrites result", async () => {
187
+ const { api } = mockApi();
188
+
189
+ api.before((_method, params) => ({ ...params, injected: true }));
190
+ api.after((_method, _params, result) => ({ ...(result as object), tagged: true }));
191
+
192
+ const result = await api.sendMessage({ chat_id: 1 });
193
+
194
+ assert.deepEqual(result, { message_id: 1, tagged: true });
195
+ });
196
+
197
+ test("channelPostUpdate / editedMessageUpdate build the right update key", () => {
198
+ assert.equal(channelPostUpdate({ text: "hi" }).channel_post?.text, "hi");
199
+ assert.equal(channelPostUpdate().channel_post?.chat.type, "channel");
200
+ assert.equal(editedMessageUpdate({ text: "hi" }).edited_message?.text, "hi");
201
+ });
202
+
203
+ test("inlineQueryUpdate / chosenInlineResultUpdate build their payloads", () => {
204
+ const iq = inlineQueryUpdate({ query: "cats", fromId: 5 });
205
+ assert.equal(iq.inline_query?.query, "cats");
206
+ assert.equal(iq.inline_query?.from.id, 5);
207
+
208
+ const cir = chosenInlineResultUpdate({ resultId: "r1", query: "cats" });
209
+ assert.equal(cir.chosen_inline_result?.result_id, "r1");
210
+ });
211
+
212
+ test("shippingQueryUpdate / preCheckoutQueryUpdate build valid payloads", () => {
213
+ const sq = shippingQueryUpdate({ shippingAddress: { city: "Berlin" } });
214
+ assert.equal(sq.shipping_query?.shipping_address.city, "Berlin");
215
+
216
+ const pcq = preCheckoutQueryUpdate({ currency: "EUR", totalAmount: 500 });
217
+ assert.equal(pcq.pre_checkout_query?.currency, "EUR");
218
+ assert.equal(pcq.pre_checkout_query?.total_amount, 500);
219
+ });
220
+
221
+ test("pollUpdate / pollAnswerUpdate build valid payloads", () => {
222
+ const poll = pollUpdate({ question: "?", options: ["a", "b", "c"] });
223
+ assert.equal(poll.poll?.options.length, 3);
224
+ assert.equal(poll.poll?.options[1]?.text, "b");
225
+
226
+ const answer = pollAnswerUpdate({ optionIds: [1] });
227
+ assert.deepEqual(answer.poll_answer?.option_ids, [1]);
228
+ });
229
+
230
+ test("myChatMemberUpdate / chatMemberUpdate / chatJoinRequestUpdate build valid payloads", () => {
231
+ const my = myChatMemberUpdate({ oldStatus: "left", newStatus: "member" });
232
+ assert.equal(my.my_chat_member?.old_chat_member.status, "left");
233
+ assert.equal(my.my_chat_member?.new_chat_member.status, "member");
234
+
235
+ const other = chatMemberUpdate({ userId: 7 });
236
+ assert.equal(other.chat_member?.new_chat_member.user.id, 7);
237
+
238
+ const join = chatJoinRequestUpdate({ chatId: 3, fromId: 4, bio: "hi" });
239
+ assert.equal(join.chat_join_request?.chat.id, 3);
240
+ assert.equal(join.chat_join_request?.bio, "hi");
241
+ });
242
+
243
+ test("messageContext / callbackContext build a Context in one call", () => {
244
+ const ctx = messageContext({ text: "hi", chatId: 9 });
245
+ assert.equal(ctx.text, "hi");
246
+ assert.equal(ctx.chat?.id, 9);
247
+
248
+ const cbCtx = callbackContext({ data: "x" });
249
+ assert.equal(cbCtx.callbackQuery?.data, "x");
250
+ });
251
+
252
+ test("findButton locates a button by text and reports its position", () => {
253
+ const markup = {
254
+ inline_keyboard: [
255
+ [{ text: "a", callback_data: "a" }],
256
+ [
257
+ { text: "b", callback_data: "b" },
258
+ { text: "Next", callback_data: "page:2" },
259
+ ],
260
+ ],
261
+ };
262
+
263
+ const found = findButton(markup, "Next");
264
+ assert.equal(found?.callback_data, "page:2");
265
+ assert.equal(found?.row, 1);
266
+ assert.equal(found?.col, 1);
267
+
268
+ assert.equal(findButton(markup, /^n/i)?.text, "Next");
269
+ assert.equal(findButton(markup, "missing"), undefined);
270
+ assert.equal(findButton(undefined, "missing"), undefined);
271
+ });
272
+
273
+ test("collectUpdates records every update handed to the sink", async () => {
274
+ const { sink, updates } = collectUpdates();
275
+
276
+ await sink.handleUpdate(messageUpdate({ text: "one" }));
277
+ await sink.handleUpdate(messageUpdate({ text: "two" }));
278
+
279
+ assert.equal(updates.length, 2);
280
+ assert.equal(updates[0]?.message?.text, "one");
281
+ });
282
+
283
+ test("webhookRequest builds a POST carrying the update as JSON, with an optional secret header", async () => {
284
+ const update = messageUpdate({ text: "hi" });
285
+ const req = webhookRequest(update, { secretToken: "s3cret" });
286
+
287
+ assert.equal(req.method, "POST");
288
+ assert.equal(req.headers.get("x-telegram-bot-api-secret-token"), "s3cret");
289
+ assert.deepEqual(await req.json(), update);
290
+ });
291
+
292
+ test("withFetch stubs globalThis.fetch for the duration of fn, then restores it", async () => {
293
+ const realFetch = globalThis.fetch;
294
+
295
+ const result = await withFetch(
296
+ async () => new Response("stubbed"),
297
+ async () => {
298
+ const res = await fetch("https://example.invalid/");
299
+ return res.text();
300
+ },
301
+ );
302
+
303
+ assert.equal(result, "stubbed");
304
+ assert.equal(globalThis.fetch, realFetch);
305
+ });
306
+
307
+ test("withFetch restores the original fetch even if fn throws", async () => {
308
+ const realFetch = globalThis.fetch;
309
+
310
+ await assert.rejects(
311
+ withFetch(
312
+ async () => new Response("x"),
313
+ () => {
314
+ throw new Error("boom");
315
+ },
316
+ ),
317
+ );
318
+
319
+ assert.equal(globalThis.fetch, realFetch);
320
+ });