mock store getter在Global Guard中不起作用



我创建了一个全局守卫,它使用了来自store的getter。

我试图从商店模拟一些getter用于测试目的。问题是mock

不工作

// 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('/');
});
})

我从这个例子中得到了启发。

谢谢@EstusFlask的评论,我解决了这个问题。

关键字是jest。测试中的mock不能影响顶级导入.

jest.mock('@/store', () => ({
getters: {
isLoggedIn: jest.fn(),
// other methods should be declared here, otherwise an exception is thrown
isSuperAdmin: jest.fn(),
isAdmin: jest.fn(),
isReadUser: jest.fn(),
},
}));
describe('should test routing functionality', () => {
it('should redirect to / when isLoggedIn is true and IsGuest is true', () => {
// given
store.getters.isLoggedIn.mockImplementation(() => () => false);
const to = {
matched: [{ meta: { guest: true } }],
};
const next = jest.fn();
// when
beforeEach(to, undefined, next);
// then
expect(next).toHaveBeenCalledWith('/');
});
})