playwright ํ…Œ์ŠคํŠธ ์ „ ํ•„์š”ํ•œ ๊ฒƒ๋“ค setupํ•˜๊ธฐ (feat. beforeMount ์‚ฌ์šฉ)

์—๋Ÿฌ ๋ฐœ์ƒ

react-router-dom๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ฝ”๋“œ์˜ playwright ํ…Œ์ŠคํŠธ ์ค‘ ์•„๋ž˜์™€ ๊ฐ™์ด useNavigate ๊ด€๋ จ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.

 

๋‹จ์ˆœ ํ•ด๊ฒฐ

useNavigate๋Š” react-router-dom ์˜ ํ›…์œผ๋กœ ์„œ์นญํ•ด๋ณด๋‹ˆ MemoryRouter ๋กœ ๊ฐ์‹ธ์ฃผ๋ฉด ๋œ๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

  const component = await mount<HooksConfig>(
    <MemoryRouter initialEntries={['/']}>
      <Component />
    </MemoryRouter>,
    { hooksConfig }
  );

 

์ด๋ ‡๊ฒŒ mount ์‹œ์— ๋‹จ์ˆœํžˆ ๊ฐ์‹ธ๋Š” ์‹์œผ๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜๋„ ์žˆ๊ฒ ์ง€๋งŒ, ์ด ๋ถ€๋ถ„์„ ๊ณตํ†ตํ™” ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

๊ณตํ†ตํ™” ์‹œ๋„ 1

import { MemoryRouter } from 'react-router-dom';
import { AuthContext } from '@contexts';

export const TEST_CT_USER_ID = 1;

export const testCtRender = (
  children: React.ReactElement,
  initialPath?: string
): React.ReactElement => {
  return (
    <MemoryRouter initialEntries={[initialPath ?? '/']}>
      <AuthContext.Provider
        value={{
          user: {
            id: TEST_CT_USER_ID,
          },
          isLoading: false,
          isError: false,
          logout: () => {},
        }}
      >
        {children}
      </AuthContext.Provider>
    </MemoryRouter>
  );
};

// ์‚ฌ์šฉ์ฒ˜
const component = await mount<HooksConfig>(
    testCtRender(<Component />, '/some-path'),
    { hooksConfig }
);

 

์šฐ์„  ๋‹จ์ˆœํžˆ render ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜๋ฅผ ๋ณ„๋„๋กœ ๊ตฌ์„ฑํ•˜์—ฌ ๊ณตํ†ตํ™”ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

testCtRender ํ•จ์ˆ˜๋Š” MemoryRouter ๋กœ ํ˜„์žฌ path ๋ฅผ ์„ธํŒ…ํ•˜๊ณ , ํ•„์š”ํ•œ Context ๋ฅผ ์ œ๊ณตํ•ด์ฃผ๋Š” ์—ญํ• ์„ ํ•ฉ๋‹ˆ๋‹ค.

 

๊ณตํ†ตํ™” ์‹œ๋„ 2

import { beforeMount as beforeMount17 } from '@playwright/experimental-ct-react17/hooks';
import { beforeMount as beforeMount18 } from '@playwright/experimental-ct-react/hooks';

interface HooksConfig {
  initialPath?: string;
}

function customBeforeMount(originalSetupApp: SetupAppCallback): void {
  beforeMount<HooksConfig>(async ({ App, hooksConfig }) => {
    const { initialPath } = hooksConfig;
    return (
        <MemoryRouter initialEntries={[initialPath ?? '/']}>
          <AuthContext.Provider
            value={{
              user: {
                id: TEST_CT_USER_ID,
              },
              isLoading: false,
              isError: false,
              logout: () => {},
            }}
          >
            <App />
          </AuthContext.Provider>
        </MemoryRouter>
    );
  });
}

// playwright/index.tsx ์—์„œ ์‹คํ–‰
customBeforeMount();

playwright ์˜ beforeMount ๊ธฐ๋Šฅ์„ ์ด์šฉํ•˜๋ฉด ๊ณตํ†ตํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•˜์ง€ ์•Š๊ณ ๋„ ๋ชจ๋“  ํ…Œ์ŠคํŠธ ์ฝ”๋“œ์— ๋˜‘๊ฐ™์€ ์ฝ”๋“œ๋ฅผ ์ ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฐธ๊ณ  : https://playwright.dev/docs/test-components

๋ฐ˜์‘ํ˜•