はじめに
ゆとり世代の中野です。
今回チャレンジした内容は【ExpoのProjectにJestを導入する】です。
さっそくチャレンジについて書いていきます。
チャレンジする背景
テストコードを書ける環境がほしい
チャレンジ内容
- テストを実行できるようにする
結論
- できました
やり方
packageの追加
- 必要なpackageをインストールする
expo install jest-expo jest
yarn add --dev ts-node
- package.jsonのscriptsにtestを追加
...
"scripts": {
"test": "jest",
...
Jestの設定ファイルを作成
- jest.config.tsをProjectのルートディレクトリに作成
import { Config } from '@jest/types';
// By default, all files inside `node_modules` are not transformed. But some 3rd party
// modules are published as untranspiled, Jest will not understand the code in these modules.
// To overcome this, exclude these modules in the ignore pattern.
const untranspiledModulePatterns = [
'(jest-)?react-native',
'@react-native-community',
'expo(nent)?',
'@expo(nent)?/.*',
'react-navigation',
'@react-navigation/.*',
'@unimodules/.*',
'unimodules',
'sentry-expo',
'native-base',
'react-native-svg',
'@react-native',
'react-native',
];
const config: Config.InitialOptions = {
preset: 'jest-expo',
transformIgnorePatterns: [`node_modules/(?!${untranspiledModulePatterns.join('|')})`],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
};
export default config;
テストを追加する
- 対象の未編集状態のApp.tsx
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text>Open up App.tsx to start working on your app!</Text>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
- App.tsxにApp.test.tsxというファイルを作りテストコードを書きます
import React from 'react';
import renderer from 'react-test-renderer';
import App from './App';
describe('<App />', () => {
it('has 1 child', () => {
const tree = renderer.create(<App />).toJSON();
expect(tree.children.length).toBe(1);
});
});
テストを実行する
yarn test App.
- PASSしていたら成功
参考元
Testing with Jest - Expo Documentation
This guide explains how to set up Jest in your project, write a unit test, write a snapshot test, and common problems people encounter when using Jest in React Native. Jest is the most widely used JavaScript unit testing framework, so you may already be familiar with it.
docs.expo.dev
Expo の TypeScript プロジェクトで自動テスト
最近は Expo で React Native もやってます 🙂 今回は、Expo のプロジェクトを Jest でテストしたい。基本的に Testing with Jest - Expo Documentation にしたがって進めればいいのだが、TypeScript の場合は多少設定を変える必要がある。この記事では以下のポイントを紹介する。 Expo の TypeScript プロジェクトで Jest を使うときの設定 Jest の設定ファイルも TypeScript で書く方法 なお、手元の環境は次の通り。 $ expo --version 4.0.17 $ npm list expo my-expo-app └── expo@40.0.0 まずは、必要なパッケージをインストールする。jest パッケージではなく jest-expo をインストールするのが Expo 流。 $ npm i
zenn.dev
まとめ
- 必要なpackageを追加する
- 設定ファイルを作成する
- テストコードを書く
- 実行する
さいごに
ExpoでもJestを使ってテストが書ける環境が作れました
yutanakano
WEBエンジニア
大阪生まれのゆとり世代です
趣味はバイクでツーリングに行くこと
愛車は Ninja ZX-25R SE KRT EDITION
Expoでプロダクトを作っています