/ duper-js-node / tests / parse.test.ts
parse.test.ts
 1  import { parse } from "..";
 2  
 3  describe("parse", () => {
 4    it("parses an empty object", () => {
 5      const duper = parse("{}");
 6      expect(duper.type).toEqual("Object");
 7    });
 8  
 9    it("parses into a JSON-stringifiable object", () => {
10      const duper = parse(`
11        Product({
12          product_id: Uuid("1dd7b7aa-515e-405f-85a9-8ac812242609"),
13          name: "Wireless Bluetooth Headphones",
14          brand: "AudioTech",
15          price: Decimal("129.99"),
16          dimensions: (18.5, 15.2, 7.8),  // In centimeters
17          weight: Kilograms(0.285),
18          in_stock: true,
19          specifications: {
20            battery_life: Duration("30h"),
21            noise_cancellation: true,
22            connectivity: ["Bluetooth 5.0", "3.5mm Jack"],
23          },
24          image_thumbnail: Png(b64"iVBORw0KGgoAAAANSUhEUgAAAGQ="),
25          tags: ["electronics", "audio", "wireless"],
26          release_date: Date("2023-11-15"),
27          /* Warranty is optional */
28          warranty_period: null,
29          customer_ratings: {
30            latest_review: r#"Absolutely ""astounding""!! 😎"#,
31            average: 4.5,
32            count: 127,
33          },
34          created_at: Instant('2023-11-17T21:50:43+00:00'),
35        })
36      `);
37      expect(duper.type).toEqual("Object");
38      expect(duper.identifier).toEqual("Product");
39      expect(JSON.stringify(duper)).toMatchSnapshot();
40    });
41  
42    it("doesn't parse invalid Duper values", () => {
43      expect(() => parse(``)).toThrow();
44      expect(() => parse(`{`)).toThrow();
45      expect(() => parse(`]`)).toThrow();
46      expect(() => parse(`tru`)).toThrow();
47      expect(() => parse(`.618`)).toThrow();
48      expect(() => parse(`Something(1, 2)`)).toThrow();
49      expect(() => parse(`Instant('2025-11-16')`)).toThrow();
50      expect(() => parse(`Iñvalid({})`)).toThrow();
51    });
52  });