SolidJSS
SolidJS16mo ago
61 replies
Vex

How do one test a custom primitives?

Hi,
I made an extension atop createStore for arrays as I use them a lot, and to provide some useful api for mutating it correctly. (I found general store use for this a little messy)
The question is - how do I test if reactivity is preserved?
More specifically, I have this test, which currently fails because the createEffect does not trigger and I don't quite know whether the test is wrong, or the implementation is (it could be both):

The test
  it('should be reactive', () => {
    createRoot((dispose) => {
      const store = createArrayStore<{ id: number }>();
      let effectCount = 0;
      createEffect(() => {
        store.get();
        effectCount++;
      });

      store.add({ id: 1 });
      expect(effectCount).toBe(1); // Initial effect + one for the add

      store.mutateElement({ id: 1 }, (el) => ({ ...el, id: 2 }));
      expect(effectCount).toBe(2);

      dispose();
    });
  });

A subset of the code:
export function createArrayStore<T extends object>(initValue?: T[]): ArrayStore<T> {
    const [currentValue, setStore] = createStore<T[]>(initValue ?? []);
    return {
        get: () => currentValue,
        set: setStore,
        add: (value: T) => {
            setStore(prev => [...prev, value]);
            return () => { //Returns a function for removing the element again
                setStore(prev => prev.filter((v) => v !== value));
            };
        },
        ...
   }
}
Was this page helpful?