IT이야기

Global Guard 내부 모의 상점 게이터가 작동하지 않음

cyworld 2022. 5. 12. 22:01
반응형

Global Guard 내부 모의 상점 게이터가 작동하지 않음

나는 가게에서 게이터를 사용하는 글로벌 가드를 만들었다.

나는 시험 삼아 가게에서 물건을 사는 사람들을 놀리려고 한다.문제는 조롱하는 것이다.

효과가 없다.

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

참조URL: https://stackoverflow.com/questions/69583704/mock-store-getters-inside-global-guard-does-not-work

반응형