Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

2.4 KB
Raw Blame
/* Copyright 2026 Marimo. All rights reserved. */

import type { TopLevelSpec } from "vega-lite";
import { describe, expect, it } from "vitest";
import {
  augmentSpecWithData,
  createSpecWithoutData,
  X_AXIS_REQUIRED,
  Y_AXIS_REQUIRED,
} from "../chart-spec/spec";
import type { ChartSchemaType } from "../schemas";
import { ChartType, NONE_VALUE } from "../types";

describe("create vega spec", () => {
  // Sample data for testing
  const sampleData = [
    { category: "A", value: 10, group: "Group 1" },
    { category: "B", value: 20, group: "Group 1" },
    { category: "C", value: 15, group: "Group 1" },
    { category: "A", value: 5, group: "Group 2" },
    { category: "B", value: 10, group: "Group 2" },
    { category: "C", value: 25, group: "Group 2" },
  ];

  // Helper function to create basic form values
  const createBasicFormValues = (): ChartSchemaType => ({
    general: {
      title: "Test Chart",
      xColumn: {
        field: "category",
        type: "string" as const,
      },
      yColumn: {
        field: "value",
        type: "number" as const,
        aggregate: NONE_VALUE,
      },
    },
  });

  it("should create and augment a spec", () => {
    const spec = createSpecWithoutData({
      chartType: ChartType.BAR,
      formValues: createBasicFormValues(),
      theme: "light",
      width: 400,
      height: 300,
    });
    expect(spec).toMatchSnapshot();
    expect(typeof spec !== "string").toBe(true); // Not error message
    expect((spec as TopLevelSpec).data).toEqual({ values: [] });

    // Augment the spec with data
    const augmentedSpec = augmentSpecWithData(spec as TopLevelSpec, sampleData);
    expect(augmentedSpec.data).toEqual({ values: sampleData });
  });

  it("should return an error message if the spec is invalid", () => {
    const formValues = createBasicFormValues();
    formValues.general!.xColumn!.field = undefined;

    const spec = createSpecWithoutData({
      chartType: ChartType.BAR,
      formValues,
      theme: "light",
      width: 400,
      height: 300,
    });
    expect(spec).toEqual(X_AXIS_REQUIRED);

    // Undefined yColumn
    const formValues2 = createBasicFormValues();
    formValues2.general!.yColumn!.field = undefined;
    const spec2 = createSpecWithoutData({
      chartType: ChartType.BAR,
      formValues: formValues2,
      theme: "light",
      width: 400,
      height: 300,
    });
    expect(spec2).toEqual(Y_AXIS_REQUIRED);
  });
});