Post

Unit Test: Setup React Native Apps for Testing

React Native 프로젝트 생성 후 Jest를 이용한 Unit Test Setup에 대하여 기록한다. Facebook에서도 React Native application을 테스트 할때 Jest를 사용하는 만큼 Jest의 역활이 크다고 생각된다.

Setup

1
2
3
4
5
6
7
8
9
{
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watchAll"
  },
  "jest": {
    "preset": "react-native"
  }
}
  • --watchAll option enables to specify the name or path to a file to focus on a specific set of tests.

혹은

1
2
3
module.exports = {
  preset: "react-native",
};

Snapshot Test

1
2
3
4
5
6
7
8
import React from "react";
import renderer from "react-test-renderer";
import Intro from "../Intro";

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

Preset configuration

transformIgnorePatterns customization

jest-react-native의 preset 초기값은 react-native로 세팅되 있으나, npm dependencies로 인한 custom preset 필요시 transformIgnorePatterns 옵션으로 커스터마이징 할 수 있다.

1
2
3
4
5
{
  "transformIgnorePatterns": [
    "node_modules/(?!(react-native|my-project|react-native-button)/)"
  ]
}

setupFiles

매 테스트에 additional configuration 추가를 원할시 setupFiles로 setup script를 작성할 수 있다.

moduleNameMapper

사용하는 module의 위치가 다를경우 moduleNameMapper option을 통해 지정해 줄 수 있다.

1
2
3
4
5
{
  "moduleNameMapper": {
    "my-module.js": "<rootDir>/path/to/my-module.js"
  }
}

Mock native module

만약 테스트 하는 컴포넌트에서 react-native-video dependency를 사용한다면 아래와 같은 방법으로 manual mock을 할 수 있다.

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

Reference

This post is licensed under CC BY 4.0 by the author.