gitlab-api-async-iterator
Version:
Async iterator for GitLab API based on axios
65 lines (54 loc) • 1.86 kB
JavaScript
import { describe, it } from "node:test";
import { deepEqual, equal } from "node:assert/strict";
import { GitLabPagedAPIIterator } from "./iteratorFactory.js";
const createAxiosMock = (...pages) => {
let callCount = 0;
return {
get: async () => {
const ret = pages.shift();
callCount += 1;
if (!ret) {
throw new Error("Unknown request result");
}
return { data: ret };
},
called: () => callCount,
};
};
describe("GitLabPagedAPIIterator", () => {
it("iterates through multiple pages", async () => {
const mockPages = [["foo", "bar"], ["baz"], []];
const GitLabAPI = createAxiosMock(...mockPages);
const iterator = new GitLabPagedAPIIterator(GitLabAPI, "/foo");
const res = [];
for await (const item of iterator) {
res.push(item);
}
deepEqual(res, ["foo", "bar", "baz"]);
equal(GitLabAPI.called(), 3, "Should have called API 3 times");
});
it("respects maxPages parameter", async () => {
const mockPages = [["foo", "bar"], ["baz"], []];
const GitLabAPI = createAxiosMock(...mockPages);
const iterator = new GitLabPagedAPIIterator(GitLabAPI, "/foo", {
maxPages: 2,
});
const res = [];
for await (const item of iterator) {
res.push(item);
}
deepEqual(res, ["foo", "bar"]);
equal(GitLabAPI.called(), 1, "Should have called API exactly once");
});
it("stops iterating if a page is empty", async () => {
const mockPages = [["foo", "bar"], [], ["this-page-will-not-be-retrieved"]];
const GitLabAPI = createAxiosMock(...mockPages);
const iterator = new GitLabPagedAPIIterator(GitLabAPI, "/foo");
const res = [];
for await (const item of iterator) {
res.push(item);
}
deepEqual(res, ["foo", "bar"]);
equal(GitLabAPI.called(), 2, "Should have called API twice");
});
});