【发布时间】:2021-12-03 14:21:38
【问题描述】:
我创建了一个使用 store 中的 getter 的全局守卫。
我试图从商店模拟一些吸气剂以进行测试。问题是嘲笑
不工作。
// router/index.ts
export function beforeEach(to: any, from: any, next: any) {
const isLoggedIn = store.getters.isLoggedIn();
const isGuest = to.matched.some((record: any) => (record.meta.guest));
if (isLoggedIn) { // isLoggedIn is always false
if (isGuest) {
next('/');
}
}
}
}
//router/index.spec.ts
describe('shoud test routing functionality', () => {
it('should redirect to / when isLoggedIn is true and IsGuest is true', () => {
// given
jest.mock('@/store', () => ({
getters: {
isLoggedIn: jest.fn().mockImplementation(
() => true, // <----------- this value is always false
),
},
}));
// even this one does not work
// jest.spyOn(getters, 'isLoggedIn').mockImplementation(() =>
// ()=> true);
const to = {
matched: [{ meta: { guest: true } }],
};
const next = jest.fn();
// when
beforeEach(to, undefined, next);
// then
expect(next).toHaveBeenCalledWith('/');
});
})
我的灵感来自这个example。
【问题讨论】:
-
测试中的 jest.mock 不会影响顶级导入。
标签: vue.js jestjs vuex vue-test-utils vue-testing-library