본문 바로가기

[JEST] next-router-mock으로 next/link 테스트 (버그 issue 진행 중)

[JEST] next-router-mock으로 next/link 테스트 (버그 issue 진행 중)

요즘 이슈가 생기면 제일 먼저 확인해보는 곳이 해당 깃헙에 들어가서 이슈 검색을 해보는 것이다.

특히, nextjs13 같은 경우에는 블로그 등 최신 이슈 관련하여 올라온 자료들이 거의 없을 때도 있어서

우선 관련 깃헙에 들어가보면 stackoverflow보다도 더 빠르게 찾을 수 있다!

 

오늘도 다시 한 번 되새기자

나는 혼자가 아니야!

 

 

문제 상황

테스트하고자 했던 상황은 간단했다.

  • 바로 nav 바의 'dots'를 누르면 '/dots' 링크로 이동하는 지 jest(v29.7.0)로 테스트 하는 것!

import Link from 'next/link';

// import한 상수 -> const navMenus = ['roadmap', 'dots']; 
import { navMenus } from '@/constants/navMenus';
import Logo from '../common/logo/Logo';
import styles from './Header.module.scss';

const Header = () => {
  return (
    <header className={styles['header-nav']}>
      <div className={styles['nav-box']}>
        <div className={styles['logo-box']}>
          <Logo />
        </div>
        <nav className={styles['menu-box']}>
          {navMenus.map((menu) => (
            <Link data-text={menu} href={`/${menu}`} key={menu} className={styles.menu}>
              <span className={styles.highlight} />
              {menu}
            </Link>
          ))}
        </nav>
      </div>
    </header>
  );
};

export default Header;

 

  • 라우팅을 시뮬레이션하고 테스팅해주는 next-router-mock(v0.9.9)로 해결하면 되는 문제였다.
  • 프리페칭 등 최적화 기능을 제공해주는 next/link를 사용했기 때문에 해당 라이브러리의 next/js 파트를 참고하여 코드를 그대로 가져왔다. (아래 오른쪽 참고)

 

억울하게도 Cannot find module... 에러가 떴다. 이미 해당 에러 메시지로 첫 번째 테스트에서 고통스럽게 해결하며 해탈했기 때문에 두 번째로 이 메시지를 봤을 때 정말 아무 생각이 없었다. ㅋㅋㅋ

 

해결 과정

나 같은 사람 꼭 한 사람은 있었겠지, 아니면 내가 질문 올리고~ 하는 가벼운 마음으로 해당 이슈를 찾아보는데, next-router-mock 깃헙 레포지토리에서 완전 따끈따끈하게 이슈가 진행되고 있었다.

 

https://github.com/scottrippey/next-router-mock/issues/104
 

Next 13.4.20-canary.20 issue · Issue #104 · scottrippey/next-router-mock

Any idea how to make the next-router-module work with the next@13.4.20-canary.20 or later? I'm getting this error: Cannot find module 'next/dist/shared/lib/router-context' from 'node_modules/next-r...

github.com

 

아, 역시 혼자가 아니었어.. ㅠㅠㅠㅠㅠㅠㅠ

이틀 전까지 올라온 많은 슨배륌들의 발자취를 보니 든든했다,,

 

문제 해결

결론적으로 아래와 같이 코드를 추가하여 해결했다!

 

테스트 통과!

 

틀린 경로를 입력하면 아래와 같이 출력이 된다.

 

+ JEST next/link 라우팅 테스트 코드

혹시나 라우팅 테스트에서(ㅠㅠㅠ) 시간낭비하는 사람이 없길 바라며, 우선 코드를 올려본다!

import { fireEvent, screen, render } from '@testing-library/react';
import mockRouter from 'next-router-mock';
import { MemoryRouterProvider } from 'next-router-mock/MemoryRouterProvider';
import Header from '@/components/header/Header';

jest.mock(
  'next/dist/shared/lib/router-context',
  () => jest.requireActual('next/dist/shared/lib/router-context.shared-runtime'),
  { virtual: true },
);

it('NextLink 테스트', async () => {
  await render(<Header />, {
    wrapper: MemoryRouterProvider,
  });
  fireEvent.click(screen.getByText('dots'));
  expect(mockRouter.asPath).toEqual('/dots');
});
728x90
⬆︎