티스토리 뷰

Build a simple component

We’ll build our UI following a Component-Driven Development (CDD) methodology. It’s a process that builds UIs from the “bottom up” starting with components and ending with screens. CDD helps you scale the amount of complexity you’re faced with as you build out the UI.

=> 우리는 UI를 개발하는데 있어 Component-Driven Development (CDD) 방법론을 따른다. 이 것은 컴포넌트들을 "아래에서 위로" 시작하여 화면으로 끝나는 UI를 구현하는 프로세스이다. CDD는 UI를 구현할 때 직면하게되는 복잡성을 줄이는데 도움을 준다.

Task

Task is the core component in our app. Each task displays slightly differently depending on exactly what state it’s in. We display a checked (or unchecked) checkbox, some information about the task, and a “pin” button, allowing us to move tasks up and down the list. Putting this together, we’ll need these props:

  • title – a string describing the task
  • state - which list is the task currently in and is it checked off?

As we start to build Task, we first write our test states that correspond to the different types of tasks sketched above. Then we use Storybook to build the component in isolation using mocked data. We’ll “visual test” the component’s appearance given each state as we go.

This process is similar to Test-driven development (TDD) that we can call “Visual TDD”.

=> 태스크는 우리 앱의 중요 컴포넌트이다. 각각의 태스크는 그 것이 어떤 상태냐(state)에 따라 약간 다를게 표시됩니다. 우리는 체크박스에 체크(또는 언체크), 태스크에 대한 몇가지 정보, '핀' 버튼을 표시하여 태스크들을 위아래로 이동할 수 있게 합니다.??? 이를 종합해보면 우리는 다음과같은 props가 필요합니다:

  • title – a string describing the task
  • state - 현재 어떤 목록이 선택되었고 어떤 목록이 해제 되었나요?;

우리가 태스크 구현을 시작할 때, 위에서 설명한 여러 타입의 Task에 부합하는 테스트 상태를 먼저 작성합니다. 그런 다음 mocked 데이터를 사용하여 격리된 컴포턴트를 빌드하기 위해 Storybook를 사용합니다. 각각의 상태에 따라 컴포넌트의 모양을 "비주얼 테스트" 합니다.

이 프로세스는 Test-driven development (TDD)와 비슷합니다. 우리는 "비주얼 TDD"로 부릅니다.

Get setup

First, let’s create the task component and its accompanying story file: src/components/Task.jsand src/components/Task.stories.js.

We’ll begin with a basic implementation of the Task, simply taking in the attributes we know we’ll need and the two actions you can take on a task (to move it between lists):

=> 우선 스토리를 수반하는 태스크 컴포넌트를 만들자 file: src/components/Task.js and src/components/Task.stories.js.

태스크의 기본 구현부터, 우리가 필요한 속성을 넣고 태스크에 대해 수행할 수 있는 두개의 조치 간단히 취하는 것으로 시작한다.(컴포넌트의 목록간의 이동을 위해)

Above, we render straightforward markup for Task based on the existing HTML structure of the Todos app.

=> 위와 같이, Todos 앱의 기존 HTML 구조에 기반하여 Task에 대한 간단한 마크 업을 렌더링한다.

Below we build out Task’s three test states in the story file:

There are two basic levels of organization in Storybook. The component and its child stories. Think of each story as a permutation of a component. You can have as many stories per component as you need.

=> 두개의 기존 레벨의 Storybook 구성이 있습니다. 컴포넌트와 하위 스토리들. 각 스토리들을 컴포넌트의 순열(?)로써 생각하세요. 각 컴포넌트마다 니가 필요한 많은 스토리가 있을 것이다.

  • Component

    • Story
    • Story
    • Story

To initiate Storybook we first call the storiesOf() function to register the component. We add a display name for the component –the name that appears on the sidebar in the Storybook app.

=> Storybook을 시작하기 위해서 우선 'storiesOf()' 함수를 호출하여 컴포넌트를 등록하세요. 그 컴포넌트의 표시 이름을 추가합니다 - Storybook 앱의 세로막대에 표시되는 이름

action() allows us to create a callback that appears in the actions panel of the Storybook UI when clicked. So when we build a pin button, we’ll be able to determine in the test UI if a button click is successful.

=> 'action()'은 클릭하면 Storybook UI의 'action' 패널이 나타나는 콜백을 만들 수 있다. 그래서 pin 버튼을 만들면, 테스트 UI에서 버튼 클릭이 성공했는지 알 수 있다.

As we need to pass the same set of actions to all permutations of our component, it is convenient to bundle them up into a single actions variable and use React's {...actions} props expansion to pass them all at once. <Task {...actions}> is equivalent to <Task onPinTask={actions.onPinTask} onArchiveTask={actions.onArchiveTask}>.

=> 우리 컴포넌트의 모든 순열에 동일한 일년의 actions들을 전달해야 하므로, 하나의 actions 변수에 묶고 React의 {...actions} props 확장(전개 연산자)를 사용하여 한번에 모두 전달하는 것이 편리하다. <Task {...actions}>는 {Task onPinTask={actions.onPinTask} onArchiveTask={actions.onArchiveTask}>와 동일하다. 

Another nice thing about bundling the actions that a component needs is that you can export them and use them in stories for components that reuse this component, as we'll see later.

=> 컴포넌트가 필요로하는 actions를 묶는것이 또 다른 좋은 점은, 나중에 알수 있듯이 이 컴포넌트를 재사용하는 (상위?)컴포넌트들를 위한 스토리에서 사용하거나 내보낼 수 있다는 것이다. 

To define our stories, we call add() once for each of our test states to generate a story. The action story is a function that returns a rendered element (i.e. a component class with a set of props) in a given state---exactly like a React Stateless Functional Component.

=> 우리의 스토리들을 정의하기위해, 스토리 생성을 위한 각 테스트 상태에 대한 add()를 호출한다. action 스토리는 state가(React Stateless Functional Component 같은) 주어진 렌더링한 element를(예를들어 일년의 props를 가진 클래스 컴포넌트) 리턴하는 함수이다.

When creating a story we use a base task (task) to build out the shape of the task the component expects. This is typically modelled from what the true data looks like. Again, export-ing this shape will enable us to reuse it in later stories, as we'll see.

=> 스토리를 생성할 때 기본 태스크를 사용하여 컴포넌트가 기대하는 결과 모양을 만듭니다. 이것은 일반적으로 실제 데이터가 어떻게 생겼는지에 따라 모델링됩니다. 다시 말하자면, 이 모양을 exporing하면 우리가 보게될 것처럼 나중에 스토리에서 다시 상용할 수 있다.

Actions help you verify interactions when building UI components in isolation. Oftentimes you won't have access to the functions and state you have in context of the app. Use action() to stub them in.

=> Actions는 격리된 UI 컴포넌트들을 구현할때 상호작용을 확인하는 데 도움이 된다.

Config

We also have to make one small change to the Storybook configuration setup (.storybook/config.js) so it notices our .stories.js files and uses our CSS file. By default Storybook looks for stories in a /stories directory; this tutorial uses a naming scheme that is similar to the .test.js naming scheme favoured by CRA for automated tests.

=> 또한 Storybok 구성 설정(.storybook/config.js)을 약간 변경해야 우리의 .stories.js파일에 주의하고 CSS 파일을 사용할 수 있다. 기본적으로 Storybook은 /stories 디렉토리의 스토리를 찾습니다. 이 tutorieal에서는 자동화된 테스트를 위해 CRA에서 선호하는 .test.js명명 체계와 유사항 명명 체계를 사용합니다.

Once we’ve done this, restarting the Storybook server should yield test cases for the three Task states:

=> 일단 Storybook 서버를 다시 시작하면 세가지 작업 상태에 대한 테스트 케이스가 생성됩니다.

https://www.learnstorybook.com/inprogress-task-states.mp4

Build out the states

Now we have Storybook setup, styles imported, and test cases built out, we can quickly start the work of implementing the HTML of the component to match the design.

=> Storybook 설정, 가져온 스타일 및 테스트케이스를 완성 했으므로 이제 디자인과 일치하도록 컴포넌트의 HTML을 구현하는 작업을 신속하게 시작하 수 있습니다.

The component is still basic at the moment. First write the code that achieves the design without going into too much detail:

=> 현재 구성요소는 여전히 기본입니다. 먼저 너무 많은 세부사항을 거치지 않고 디자인을 구현하는 코드를 작성하십시오.

The additional markup from above combined with the CSS we imported earlier yields the following UI:

=> 위에서 추가한 마크 업과 앞서 가져온 CSS를 결합하면 다음과 같은 UI가 생성됩니다.

https://www.learnstorybook.com/finished-task-states.mp4

Specify data requirements

It’s best practice to use propTypes in React to specify the shape of data that a component expects. Not only is it self documenting, it also helps catch problems early.

=> React에서 propType을 사용하여 컴포넌트가 예상하는 데이터의 모양을 지정하는 것이 가장 좋습니다. 자체 문서화 일뿐만 아니라 문제를 조기에 발견하는데도 도움이 됩니다.

Now a warning in development will appear if the Task component is misused.

An alternative way to achieve the same purpose is to use a JavaScript type system like TypeScript to create a type for the component properties.

=> 태스크 컴포넌트를 잘못 사용하면 개발 중 경고 메시지가 나타납니다.

또 다른 방법은 Typescript와 같은 Javascript 유형 시스템을 사용하여 컴포넌트 속성의 Type을 만드는 것입니다.

Component built!

We’ve now successfully built out a component without needing a server or running the entire frontend application. The next step is to build out the remaining Taskbox components one by one in a similar fashion.

As you can see, getting started building components in isolation is easy and fast. We can expect to produce a higher-quality UI with less bugs and more polish because it’s possible to dig in and test every possible state.

=> 이제 서버가 필요 없거나 전체 프론트엔드 애플리케이션을 실행하지 않고도 구성요소를 성공적으로 구축했습니다. 다음 단계는 비슷한 방식으로 나머지 Taskbox 구성 요소를 하나씩 구성하는 것입니다.

보시다시피, 구성 요소를 결리 된 상태에서 시작하는 것은 쉽고 빠릅니다. 가능한 모든 상태를 파고 테스트 할 수 있기 때문에 버그가 적고 세련된 UI를 제공 할 수 있습니다.

Automated Testing

Storybook gave us a great way to visually test our application during construction. The ‘stories’ will help ensure we don’t break our Task visually as we continue to develop the app. However, it is a completely manual process at this stage, and someone has to go to the effort of clicking through each test state and ensuring it renders well and without errors or warnings. Can’t we do that automatically?

=> Storybook 을 사용하면 제작 과정에서 응용 프로그램을 시각적으로 테스트 할 수 있습니다. '이야기'는 앱 개발을 계속하면서 시각적으로 작업을 중단하지 않도록 하는데 도움이됩니다. 그러나 이 단계에서는 완전히 수동 프로세스이므로 다른 테스트 상태를 모두 클릭하여 오류나 경고없이 잘 렌더링되도록 노력해야 합니다. 자동으로 그렇게 할 수 없습니까?

Snapshot testing

Snapshot testing refers to the practice of recording the “known good” output of a component for a given input and then flagging the component whenever the output changes in future. This complements Storybook, because it’s a quick way to view the new version of a component and check out the changes.

=> 스냅 샷 테스트는 주어진 입력에 대한 컴포넌트의 '양호한'출력을 기록한 다음 장래에 출력이 변경 될 때만다 컴포넌트에 플래그를 지정하는 관행을 말합니다. 이 컴포넌트의 새 버전을 빠르게 확인하고 변경 사항을 확인하는 빠른 방법이기 때문에 Storybook을 보완합니다.

Make sure your components render data that doesn't change, so that your snapshot tests won't fail each time. Watch out for things like dates or randomly generated values.

=> 스냅 샷 테스트가 매번 실패하지 않도록 컴포넌트가 변경되지 않는 데이터를 렌더링하는지 확인하십시오. 날짜 또는 무작위로 생성되는 값과 같은 것을 조심하십시오

With the Storyshots addon a snapshot test is created for each of the stories. Use it by adding a development dependency on the package:

=> Storyshots 애드온을 사용하면 스토리마다 스냅 샷 테스트가 만들어집니다. 패키지에 추가하여 사용하십시요

yarn add --dev @storybook/addon-storyshots react-test-renderer require-context.macro

Then create an src/storybook.test.js file with the following in it:

You'll also need to use a babel macro to ensure require.context (some webpack magic) runs in Jest (our test context). Update .storybook/config.js to have:

(Notice we've replaced require.context with a call to requireContext imported from the macro).

Once the above is done, we can run yarn test and see the following output:

We now have a snapshot test for each of our Task stories. If we change the implementation of Task, we’ll be prompted to verify the changes.

=> 이제 각 태스크 스토리들에 대한 스냅 샷 테스트가 제공되었다. 태스크 구현을 변경하면 변경사항을 확인하라는 메시지가 표시된다.

'Tool > Storybook' 카테고리의 다른 글

[Storybook Doc 번역_v5.1] - Composite component  (0) 2019.07.19
Storybook 적용기  (2) 2019.07.17
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함