如何测试 vuex 插件 store.subscribe
Posted
技术标签:
【中文标题】如何测试 vuex 插件 store.subscribe【英文标题】:How to test vuex plugins 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。
【问题讨论】:
【参考方案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
);
);
);
【讨论】:
以上是关于如何测试 vuex 插件 store.subscribe的主要内容,如果未能解决你的问题,请参考以下文章
如何测试从 VueX 监视计算属性的 Vue watcher?