Files
pleno-vue/tests/unit/customer-rule-product-restriction-service.spec.js
T

97 lines
3.2 KiB
JavaScript

// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("axios", () => ({
default: {
get: vi.fn(),
put: vi.fn(),
},
}));
import axios from "axios";
import {
extractCustomerRuleProductRestrictionPayload,
listCustomerRuleProductRestrictions,
normalizeCustomerRuleProductRestrictionResponse,
serializeCustomerRuleProductRestriction,
updateCustomerRuleProductRestriction,
} from "@/features/customer/customerRuleProductRestrictionService.js";
describe("customer rule product restriction service", () => {
beforeEach(() => {
window.localStorage.clear();
vi.clearAllMocks();
});
it("unwraps both API success wrapper variants", () => {
expect(extractCustomerRuleProductRestrictionPayload({ data: { data: { rules: [1] } } })).toEqual({ rules: [1] });
expect(extractCustomerRuleProductRestrictionPayload({ data: { rules: [2] } })).toEqual({ rules: [2] });
});
it("normalizes collections, exact product ids, and available products", () => {
const normalized = normalizeCustomerRuleProductRestrictionResponse({
data: {
data: {
rules: [
{
attribute: "restrictSpotFree",
version: "2",
collections: [{ id: 5, name: "Rinses", sort_order: 1, products: [{ id: "23" }] }],
},
],
products: [
{ product_id: "23", product_name: "RO rinse" },
{ id: 0, name: "Invalid" },
],
},
},
});
expect(normalized.rules[0]).toEqual({
attribute: "restrictSpotFree",
version: 2,
collections: [{ id: 5, name: "Rinses", sort_order: 1, product_ids: [23] }],
disabled_product_ids: [23],
});
expect(normalized.products).toEqual([{ product_id: "23", product_name: "RO rinse", id: 23, name: "RO rinse" }]);
});
it("serializes atomic replacement payloads without temporary ids", () => {
expect(
serializeCustomerRuleProductRestriction({
version: 4,
collections: [
{ id: -1, name: " New ", product_ids: ["23", 23] },
{ id: 7, name: "Existing", product_ids: [24] },
],
})
).toEqual({
version: 4,
collections: [
{ name: "New", sort_order: 0, product_ids: [23] },
{ id: 7, name: "Existing", sort_order: 1, product_ids: [24] },
],
});
});
it("uses authenticated GET and versioned atomic PUT endpoints", async () => {
window.localStorage.setItem("token", "test-token");
axios.get.mockResolvedValue({ data: {} });
axios.put.mockResolvedValue({ data: {} });
await listCustomerRuleProductRestrictions();
await updateCustomerRuleProductRestriction("restrictSpotFree", { version: 3, collections: [] });
expect(axios.get).toHaveBeenCalledWith(
expect.stringMatching(/\/superuser\/customer-rules\/product-restrictions$/),
{ headers: { Authorization: "Bearer test-token" } }
);
expect(axios.put).toHaveBeenCalledWith(
expect.stringMatching(/\/superuser\/customer-rules\/product-restrictions\/restrictSpotFree$/),
{ version: 3, collections: [] },
{ headers: { Authorization: "Bearer test-token" } }
);
});
});