How to test yjs?

I have a function which converts plain data to yjs object.

import * as Y from "yjs";

export type YImage = Y.Text | Y.Map<string | null> | string;

export const getYImageComponentsImage = ({
  image,
  footnotes,
  __typename,
}): Y.Map<YImage> => {
  const yValue = new Y.Map<YImage>();

  const yImage = new Y.Map<string | null>();
  yImage.set("id", image.data?.id || null);
  yImage.set("url", image.data?.attributes.url || "");

  const yFootnotes = new Y.Text();
  yFootnotes.insert(0, footnotes);

  yValue.set("image", yImage);
  yValue.set("footnotes", yFootnotes);
  yValue.set("__typename", __typename);

  return yValue;
};

Now I need to write jest test to verify the shape of the yjs object is correct.

import { getYImageComponentsImage } from "./getYImageComponentsImage";

const initialData = {
  id: "5",
  __typename: "ComponentImageComponentsImage",
  image: {
    data: {
      id: "10",
      attributes: {
        url: "/mock/image/url.jpg",
        alternativeText: "",
        width: 1000,
        height: 600,
      },
    },
  },
  footnotes: "Morbi leo risus, porta ac consectetur ac, vestibulum at eros.",
};

describe("getImageFormReadyForRevision", () => {
  it("correctly converts components data of the image ready to save", async () => {
    const result = getYImageComponentsImage(initialData);

    expect(result.get("__typename")).toBe("ComponentImageComponentsImage");
  });
});

This function actually works in my app, but in jest not. result.get("__typename") returns undefined. What am I doing wrong?

Shared types need to be attached to a YDoc to work. Create a blank YDoc and add your type to it and it should run.

I don’t get it. Do you mean I have to create a blank YDoc right in the test?

Yes, just replace

const yValue = new Y.Map<YImage>()

with

const doc = new Y.Doc()
const yValue = doc.getMap<YImage>()

No, this function is working as expected in my app and I don’t want to change it. But I need to test it. There is already doc object which is being used in my app and I don’t need to create the new one in each function which creates a partial for this doc.

Then attach the shared type to a doc in your test:

const result = getYImageComponentsImage(initialData)

const doc = new Y.Doc()
doc.getMap().set('result', result)

expect(result.get("__typename")).toBe("ComponentImageComponentsImage");
1 Like

It works! Thank you!

1 Like