Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trouble Shooting 모음 #26

Open
jiheon788 opened this issue Mar 23, 2023 · 4 comments
Open

Trouble Shooting 모음 #26

jiheon788 opened this issue Mar 23, 2023 · 4 comments
Labels
Type: Docs 문서 작업 및 수정

Comments

@jiheon788
Copy link
Member

테스트 과정 중 생긴 문제상황, 원인, 해결방안, 레퍼런스를 Comment로 남겨주세요🙆‍♂️🙆‍♀️

@jiheon788
Copy link
Member Author

jiheon788 commented Mar 23, 2023

문제 상황

msw 테스트 환경에서 작동불가

원인

Mock Service Worker는 브라우저에서 작동하지만, 테스트는 노드 환경에서 작동

해결방안

테스트 모드에서는 서버로 가동해줘야함

// mocks/server.ts
import { setupServer } from 'msw/node';
import { handlers } from './handlers';

export const server = setupServer(...handlers);

// App.tsx
import ...

if (process.env.NODE_ENV === 'test') {
  (async () => {
    const { server } = await import('@/mocks/server');
    server.listen();
  })();
} else if (IS_MOCK) {
  (async () => {
    const { worker } = await import('@/mocks/browser');
    worker.start();
  })();
}

const App = () => {
  ....
}

// src/setupTest.ts
import '@testing-library/jest-dom';
import { server } from '@/mocks/server';

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

레퍼런스

@raw20
Copy link

raw20 commented Mar 23, 2023

문제 상황

AdminPage 컴포넌트 랜더링 테스트 중 screen.debug()를 찍으면

<body>
     <div />
</body>

요소들이 다 날라간채 debug 출력

원인

AdminPage 컴포넌트가 로딩되기 전에 테스트를 실행

해결방안

await를 처리 후 findByText를 사용하여 요소 안에 있는 텍스트를 갖고옴

describe('AdminPage 랜더링', () => {
  it('...', async () => {
    render(
      <BrowserRouter>
        <ChakraProvider theme={theme}>
          <QueryClientProvider client={queryClient}>
            <Suspense fallback="loading...">
              <TableController />
            </Suspense>
          </QueryClientProvider>
        </ChakraProvider>
      </BrowserRouter>,
    );
   ...
    const completeBtn = await screen.findByText('...');
    fireEvent.click(completeBtn);

   ...
});

@jiheon788 jiheon788 added the Type: Docs 문서 작업 및 수정 label Mar 23, 2023
@tnghgks
Copy link
Contributor

tnghgks commented Mar 23, 2023

문제 상황

초기 테스트 환경 세팅 시 문제 발생

  1. Test 파일에서 컴포넌트 render 시 모듈 경로를 못찾는 에러
    image

원인

  1. craco를 통한 import 시 절대경로 변경으로 모듈을 찾을 수 없는 원인

해결방안

  1. craco.config.js에 jest config를 추가해줌
module.exports = {
  reactScriptsVersion: 'react-scripts',
  webpack: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
    plugins: [new TsconfigPathsPlugin({ configFile: tsConfigPath })],
  },
  jest: {  
    configure:{
      moduleNameMapper: { // 이부분 추가
        "^@/(.*)$": "<rootDir>/src/$1",
      },
    }
  }
};
  1. package.json과 같은 depth에 jest.config.js 파일 생성 이 경우 package.json script 수정 필요 "test" : "jest --watch"
module.exports = {
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
  },
};

@jhoon9494
Copy link
Collaborator

문제상황

테스트는 정상적으로 동작하나 아래 사진과 같은 에러메세지가 계속 발생
스크린샷 2023-03-23 오후 5 15 52

원인

클릭 등의 이벤트를 통해 비동기적으로 컴포넌트를 업데이트 시킨 후, 구성 요소가 모두 렌더링 또는 업데이트되기 전에 테스트가 조기에 종료되어 발생함.

해결 방안

모든 렌더링 및 업데이트가 완료된 후 테스트를 종료시켜야 함.
비동기적으로 컴포넌트를 업데이트 시키는 코드 이후에 아래 코드를 작성하여 렌더링이 종료된 다음 테스트를 종료시킴.

await waitForElementToBeRemoved(() => screen.queryByText('loading...'));

참고자료

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: Docs 문서 작업 및 수정
Projects
None yet
Development

No branches or pull requests

8 participants