grocery-app/backend/tests/household.model.test.js

76 lines
2.4 KiB
JavaScript

jest.mock("../db/pool", () => ({
connect: jest.fn(),
query: jest.fn(),
}));
const pool = require("../db/pool");
const Household = require("../models/household.model");
describe("household.model household ordering", () => {
beforeEach(() => {
jest.clearAllMocks();
});
test("loads households using the user's saved sort order", async () => {
pool.query.mockResolvedValueOnce({
rows: [{ id: 2, name: "Second", household_sort_order: 0 }],
});
const households = await Household.getUserHouseholds(9);
expect(households).toEqual([{ id: 2, name: "Second", household_sort_order: 0 }]);
expect(pool.query).toHaveBeenCalledWith(
expect.stringContaining("ORDER BY hm.household_sort_order ASC NULLS LAST"),
[9]
);
});
test("persists a full household order for the current user", async () => {
const client = {
query: jest.fn()
.mockResolvedValueOnce({})
.mockResolvedValueOnce({ rows: [{ household_id: 1 }, { household_id: 2 }] })
.mockResolvedValueOnce({})
.mockResolvedValueOnce({})
.mockResolvedValueOnce({ rows: [{ id: 2 }, { id: 1 }] })
.mockResolvedValueOnce({}),
release: jest.fn(),
};
pool.connect.mockResolvedValueOnce(client);
const households = await Household.reorderUserHouseholds(9, [2, 1]);
expect(households).toEqual([{ id: 2 }, { id: 1 }]);
expect(client.query).toHaveBeenNthCalledWith(1, "BEGIN");
expect(client.query).toHaveBeenNthCalledWith(
3,
expect.stringContaining("SET household_sort_order = $1"),
[0, 9, 2]
);
expect(client.query).toHaveBeenNthCalledWith(
4,
expect.stringContaining("SET household_sort_order = $1"),
[1, 9, 1]
);
expect(client.query).toHaveBeenLastCalledWith("COMMIT");
expect(client.release).toHaveBeenCalled();
});
test("rejects an order that does not match the user's memberships", async () => {
const client = {
query: jest.fn()
.mockResolvedValueOnce({})
.mockResolvedValueOnce({ rows: [{ household_id: 1 }] })
.mockResolvedValueOnce({}),
release: jest.fn(),
};
pool.connect.mockResolvedValueOnce(client);
const households = await Household.reorderUserHouseholds(9, [1, 2]);
expect(households).toBeNull();
expect(client.query).toHaveBeenNthCalledWith(3, "ROLLBACK");
expect(client.release).toHaveBeenCalled();
});
});