2022/리액트+TDD(完)

react typescript 기본 테스트 코드

AKI 2022. 1. 5. 17:26

기본세팅

npx create-react-app todo-list --template=typescript
cd todo-list
npm install --save styled-components
npm install --save-dev @types/styled-components jest-styled-components

 

App.tsx

import React from 'react';
import logo from './logo.svg';
import Styled, {keyframes} from 'styled-components';

const Container = Styled.div`
  text-align: center;
`;

const Header = Styled.header`
  background-color: #282c34 !important;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
`;

const spin = keyframes`
  from {
      transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
`;

const AppLogo = Styled.img`
  height: 40vmin;
  pointer-events: none;

  @media (prefers-reduced-motion: no-preference) {
    animation: ${spin} infinite 20s linear;
  }
`;

const AppLink = Styled.a`
  color: #61dafb;
`;

function App() {
  return (
      <Container>
		  <Header>
			<AppLogo src={logo} alt="logo" />
			<p>
			  Edit <code>src/App.tsx</code> and save to reload.
			</p>
			<AppLink
			  href="https://reactjs.org"
			  target="_blank"
			  rel="noopener noreferrer"
			>
			  Learn React
			</AppLink>
		  </Header>
      </Container>
  );
}

export default App;

 

App.test.tsx

import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';

describe('<App />', () => {
  it('renders component correctly', () => {
    const { container } = render(<App />);

    const linkElement = screen.getByText(/learn react/i);
    expect(linkElement).toBeInTheDocument();

    const appLogo = screen.getByAltText('logo');
    expect(appLogo).toBeInTheDocument();
    expect(appLogo).toHaveAttribute('src', 'logo.svg');

    expect(container.getElementsByTagName('p')).toHaveLength(1);
    expect(container.getElementsByTagName('p')[0]).toHaveTextContent(
      'Edit src/App.tsx and save to reload.'
    );

    expect(container).toMatchSnapshot();
  });
});

tsconfig.json 에서 baseUrl 내용 추가

{
  "compilerOptions": {
    	...
	"baseUrl": "src"
  },
}
반응형