Global Guard 中的模拟商店吸气剂不起作用

mock store getters inside Global Guard does not work

我创建了一个使用 store 中的 getter 的全局守卫。

我正在尝试从商店中模拟一些 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

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