【问题标题】:How to test vuex plugins store.subscribe如何测试 vuex 插件 store.subscribe
【发布时间】:2018-12-13 15:23:50
【问题描述】:

我正在使用 jest 来测试一个 vue 应用程序,我对如何测试插件代码有疑问。这是我要测试的代码:

export const persistPlugin = store => {
  store.subscribe(async (mutation, state) => {
    // filter all keys that start with `__`
    const _state = omitPrivate(state);
    const storedState = await storage.get('state');
    if (isEqual(_state, storedState)) return;
    storage.set(store, 'state', _state);
  });
};

我坚持的是store.subscribe 部分。 store 是作为插件方法的参数传递的,但我不知道如何从测试中调用此方法是触发插件功能块的 wat。

【问题讨论】:

    标签: javascript unit-testing vue.js jestjs vuex


    【解决方案1】:

    您可以为此使用 testPlugin 助手。这是一个可以适应状态验证的示例。 我更喜欢跟踪突变而不是直接的状态变化:

    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
        );
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2019-03-17
      • 1970-01-01
      • 2017-09-15
      • 2020-06-23
      • 2021-01-06
      • 2013-10-06
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多