티스토리 뷰

Tool/jest

[번역] Jest - Testing React Native Apps

코딩산책 2018. 11. 1. 22:04


원문: https://jestjs.io/docs/en/tutorial-react-native
버전: Jest 23.6
날짜: 2018-11-01
※ 내용숙지가 안된 번역이 많아, 원문을 함께 둠

Testing React Native Apps

At Facebook, we use Jest to test React Native applications.

Get a deeper insight into testing a working React Native app example by reading the following series: Part 1: Jest – Snapshot come into play and Part 2: Jest – Redux Snapshots for your Actions and Reducers.

페이스북에서 React Native 애플리케이션 테스트를 위해 Jest를 사용한다.

React Native app 테스트 동작을 깊게 이해하기 위해서 다음 예제들을 읽어 보자: Part 1: Jest – Snapshot come into play and Part 2: Jest – Redux Snapshots for your Actions and Reducers.

Setup

Starting from react-native version 0.38, a Jest setup is included by default when running react-native init. The following configuration should be automatically added to your package.json file:

react-native 0.38 버전부터 시작하였고, Jest는 react-native init 실행할 때 기본적으로 포함된다. 다음 아래의 설정은 package.json 파일에 자동적으로 추가된다:

// package.json
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "preset": "react-native"
  }

Note: If you are upgrading your react-native application and previously used the jest-react-native preset, remove the dependency from your package.json file and change the preset to react-native instead.

Note: 만약  이전 jest-react-native preset을 사용하고 react-native 애플리케이션을 업그레이드 한다면, package.json에 dependency를 삭제하고 preset를 대신 react-native로 변경해라.

Simply run yarn test to run tests with Jest.

간단하게 yarn test 실행으로 Jest 테스트를 실행할 수 있다.

Snapshot Test

Let's create a snapshot test for a small intro component with a few views and text components and some styles:

몇개의 views와 test 컴포넌트들과 styles가 있는 작은 intro 컴포넌트를 위해 스냅샷 테스트를 만들어 보자.

// Intro.js
import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    flex: 1,
    justifyContent: 'center',
  },
  instructions: {
    color: '#333333',
    marginBottom: 5,
    textAlign: 'center',
  },
  welcome: {
    fontSize: 20,
    margin: 10,
    textAlign: 'center',
  },
});

export default class Intro extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>
          This is a React Native snapshot test.
        </Text>
      </View>
    );
  }
}

Now let's use React's test renderer and Jest's snapshot feature to interact with the component and capture the rendered output and create a snapshot file:

이제 React의 테스트 렌더러와 Jest의 스냅샷 기능을 사용하여 컴포넌트와 캡처한 렌더러 출력물이 상호작용하는 스냅샷 파일을 만들어보자:

// __tests__/Intro-test.js
import React from 'react';
import Intro from '../Intro';

import renderer from 'react-test-renderer';

test('renders correctly', () => {
  const tree = renderer.create(<Intro />).toJSON();
  expect(tree).toMatchSnapshot();
});

When you run yarn test or jest, this will produce an output file like this:

yarn test 또는 jest 실행할때, 이것과 같은 출력물을 만들 것이다.

// __tests__/__snapshots__/Intro-test.js.snap
exports[`Intro renders correctly 1`] = `
<View
  style={
    Object {
      "alignItems": "center",
      "backgroundColor": "#F5FCFF",
      "flex": 1,
      "justifyContent": "center",
    }
  }>
  <Text
    style={
      Object {
        "fontSize": 20,
        "margin": 10,
        "textAlign": "center",
      }
    }>
    Welcome to React Native!
  </Text>
  <Text
    style={
      Object {
        "color": "#333333",
        "marginBottom": 5,
        "textAlign": "center",
      }
    }>
    This is a React Native snapshot test.
  </Text>
</View>
`;

The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with jest -u to overwrite the existing snapshot.

테스트를 실행한 다음, 렌더러 출력이 이전에 작성된 스냅샷과 비교될 것이다. 스냅샷은 코드 변경에 따라 커밋해야 한다. 스냅샷이 실패할 때, 그것이 의도된 변경인지 아닌지 검토해야 한다. 만약 그 변경이 예상된 거라면 jest -u를 실행 시켜 기존 스냅샷을 덮어쓸 수 있다.

The code for this example is available at examples/react-native.

이 예제 코드는 examples/react-native 에서 볼 수 있다..

Preset configuration

The preset sets up the environment and is very opinionated and based on what we found to be useful at Facebook. All of the configuration options can be overwritten just as they can be customized when no preset is used.

프리셋은 환경을 설정하고 Facebook에서 매우 유용한다고 판단되 것들을 기반으로 매우 독창적이다. 모든 설정 옵션들은 프리셋 사용을 안할 때 사용자 설정을 할 수 있는 것처럼 덮어쓰여 질 수 있다.(??)

Environment

react-native ships with a Jest preset, so the jest.preset field of your package.json should point to react-native. The preset is a node environment that mimics the environment of a React Native app. Because it doesn't load any DOM or browser APIs, it greatly improves Jest's startup time.

react-native는 jest 프리셋으로 항해한다(??), 그래서 package.json의 jest.preset 필드는 react-native로 되어야 한다.

프리셋은 React Native app의 환경처럼 보이는 node 환경이다. 따라서 어떤 DOM 또는 APIs를 로드하지 않고, Jest 시작 타임을 매우 향상 시킨다.

transformIgnorePatterns customization

The transformIgnorePatterns option can be used to whitelist or blacklist files from being transformed with babel. Many react-native npm modules unfortunately don't pre-compile their source code before publishing.

transformIgnorePatterns 옵션은 babel을 사용하는 변형된 화이트리스트 또는 블랙리스트 파일을 위해 사용 할 수 있다. 많은 react-native npm 모듈들은 불행하게 그들의 소스코드가 퍼블리쉬되기 전에 미리 컴파일 되지 않는다.


By default the jest-react-native preset only processes the project's own source files and react-native. If you have npm dependencies that have to be transformed you can customize this configuration option by whitelisting modules other than react-native:

jest-react-native 프리셋은 기본적으로 프로젝트의 소스 파일과 react-native을 실행한다. 만약 변형해야할 npm 의존을 갖고 있다면 react-native 이외의 화이트리스트 모듈을 사용하여 이 구성 옵션을 사용자 정의 할 수 있다.

"transformIgnorePatterns": [
  "node_modules/(?!(react-native|my-project|react-native-button)/)"
]

setupFiles

If you'd like to provide additional configuration for every test file, the setupFiles configuration option can be used to specify setup scripts.

모든 테스트 파일에 구성설정을 추가하기를 원한다면,  setupFiles configuration option 은 설정 스크립트로 명시하기 위해 사용할 수 있다.

moduleNameMapper

The moduleNameMapper can be used to map a module path to a different module. By default the preset maps all images to an image stub module but if a module cannot be found this configuration option can help:

 moduleNameMapper 를 사용하여 모듈 경로를 다른 모듈에 매핑할 수 있다. 기본적으로 프리셋은 모든 이미지를 이미지 스텁 모듈에 매핑하지만 만약 그렇지 않고 찾을 수 없다면 이 설정옵션을 수행 할 수 있다.

"moduleNameMapper": {
  "my-module.js": "<rootDir>/path/to/my-module.js"
}

Tips

Mock native modules using jest.mock

The Jest preset built into react-native comes with a few default mocks that are applied on a react-native repository. However some react-native components or third party components rely on native code to be rendered. In such cases, Jest's manual mocking system can help to mock out the underlying implementation.

react-native로 Jest 프리셋 빌드는 react-native 저장소에 적용된 몇개의 기본 mocks를 제공한다. 그러나 몇개의 react-native 컴포넌트 또는 third party 컴포넌트는 렌더링된 네이티브 코드에 의존한다. 이런 경우, Jest의 수동 mocking 시스템은 기본 구현을 mock 하는데 도움이 될 수 있다.

For example, if your code depends on a third party native video component called react-native-video you might want to stub it out with a manual mock like this:

예를들어, 만약 코드가 react-native-video라는 서드파트 네이티브 video 컴포넌트에 의존적이라면, 수동 mock를 이 것과 같이 stub 하길 원할 것이다.

jest.mock('react-native-video', () => 'Video');

This will render the component as <Video {...props} /> with all of its props in the snapshot output. See also caveats around Enzyme and React 16.

스냅샷 출력에 모든 props가 있는 <Video {...props} /> 컴포넌트로써 렌더링 할 것이다. 또한 caveats around Enzyme and React 16 보자.

Sometimes you need to provide a more complex manual mock. For example if you'd like to forward the prop types or static fields of a native component to a mock, you can return a different React component from a mock through this helper from jest-react-native:

때때로 복잡한 수동 mock을 필요할 때가 있다. 예를들어 만약 mock을 위한 네이티브 컴포넌트의 props types 또는 static fields를 보내기를 원한다면, jest-react-native에서 이 핼퍼를 통해 mock와 다른 React componenet 반환할 수 있다.

jest.mock('path/to/MyNativeComponent', () => {
  const mockComponent = require('react-native/jest/mockComponent');
  return mockComponent('path/to/MyNativeComponent');
});

Or if you'd like to create your own manual mock, you can do something like this:

또는 만약 수동 mock를 생성하기 원한다면 아래와 같이 할수 있다.

jest.mock('Text', () => {
  const RealComponent = jest.requireActual('Text');
  const React = require('React');
  class Text extends React.Component {
    render() {
      return React.createElement('Text', this.props, this.props.children);
    }
  }
  Text.propTypes = RealComponent.propTypes;
  return Text;
});

In other cases you may want to mock a native module that isn't a React component. The same technique can be applied. We recommend inspecting the native module's source code and logging the module when running a react native app on a real device and then modeling a manual mock after the real module.

이와 다르게 React 컴포턴트가 아닌 mock 네이티브 모듈을 원할 수 있다. 같은 기술이 적용될 수 있다. react native 앱이 실제 장치에서 실행될때 네이티브 모듈의 소스코드를 검사하고 모듈을 로깅하고 것이 좋고 그리고 나서 실제 모듈 후에 수동 mock 모델링을 한다. 

If you end up mocking the same modules over and over it is recommended to define these mocks in a separate file and add it to the list of setupFiles.

만약 동일한 모듈을 계속해서 mocking 한다면, 이런 mocks를 setupFiles의 목록에 추가하고 파일로 나눠 정의하는 것이 좋다.

@providesModule

If you'd like to use Facebook's @providesModule module system through an npm package, the default haste config option must be overwritten and npm modules must be added to providesModuleNodeModules:

만약 npm pakage를 통해 Facebook의 @providesModule 모듈 시스템을 사용하고 싶을 경우, 기본 haste 설정옵션을 덮어써야 하고 npm 모듈을 만드시  providesModuleNodeModule에 추가해야만 한다.

"haste": {
  "defaultPlatform": "ios",
  "platforms": ["android", "ios"],
  "providesModuleNodeModules": [
    "react",
    "react-native",
    "my-awesome-module",
    "my-text-component"
  ]
},

If you'd like to test a different default platform or if you are building for other platforms, the defaultPlatformand platforms configuration option can be updated.

만약 다른 기본 플랫폼 또는 다른 플랫폼에서 빌드하기를 원한다면,  defaultPlatformand platforms 설정옵션은 업데이트 할 수 있다.


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

[번역] Jest - Testing Asynchronous Code  (0) 2018.11.09
[번역] Jest - Setup and Teardown  (0) 2018.11.08
[번역] Jest - Using Matchers  (0) 2018.11.07
[번역] Jest - Mock Functions  (0) 2018.11.05
[번역] Jest - An Async Example  (0) 2018.11.03
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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 31
글 보관함