[Vuejs]-How to test vuex plugins store.subscribe

0👍

You could use testPlugin helper for this. Here it is an example which you could adapt for the state verification.
I prefer to track mutations instead of direct state changes:

import { persistPlugin } from "@/store";

export const testPlugin = (plugin, state, expectedMutations, done) => {
  let count = 1;

  // mock commit
  const commit = (type, payload) => {
    const mutation = expectedMutations[count];

    try {
      expect(type).toEqual(mutation.type);
      if (payload) {
        expect(payload).toEqual(mutation.payload);
      }
    } catch (error) {
      done(error);
    }

    count++;
    if (count >= expectedMutations.length) {
      done();
    }
  };

  // call the action with mocked store and arguments
  plugin({
    commit,
    state,
    subscribe: cb =>
      cb(expectedMutations[count - 1], expectedMutations[count - 1].payload)
  });

  // check if no mutations should have been dispatched
  if (expectedMutations.length === 1) {
    expect(count).toEqual(1);
    done();
  }
};


describe("plugins", () => {
  it("commits mutations for some cases", done => {
    testPlugin(
      persistPlugin,
      { resume: { firstName: "Old Name" } },
      [{ type: "updateResume", payload: { firstName: "New Name" } }], // This is mutation which we pass to plugin, this is payload for plugin handler
      [{ type: "updateResume", payload: { firstName: "New Name" } }], // This is mutation we expects plugin will commit
      done
    );
  });
});

Leave a comment