はじめに
前回の記事でdetoxの導入について書きました。
自分が携わってるアプリでは、ログインの有無で表示画面の内容が変わります。
ログイン情報はreact-native-keychainで管理しているのですが、テストの冪等性を保証するために奮闘した内容を記載します。
(もっと良い解決策があればご教示いただけるとありがたいです。)
デバイスの初期化処理
初期化をするにあたり、公式ドキュメントで使えそうな関数がいくつかあります。
device.reloadReactNative();
If this is a React Native app, reload the React Native JS bundle. This action is much faster than device.launchApp(), and can be used if you just need to reset your React Native logic.
挙動としては CMD+Rによるリロードが行われているようです。
(初期画面に戻ります。クレデンシャルはリセットされません。)
device.launchApp(params)
newInstance: true
Terminate the app and launch it again. If set to false, the simulator will try to bring app from background, if the app isn't running, it will launch a new instance. default is false
この設定を入れることで、新たなインスタンスとしてアプリを起動してくれそうです。
delete: true
A flag that enables relaunching into a fresh installation of the app (it will uninstall and install the binary again), default is false.
この設定を入れることで、アプリをデリート→再インストールしてくれそうです。
上記を踏まえて、下記の形でテストを実行してみました。
describe('example', () => {
beforeEach(async () => {
await device.launchApp({
delete: true,
newInstance: true,
});
});
it('test is described here', async () => {
// ...
}
});
しかし、結果としてクレデンシャルはリセットされず…。
device.resetContentAndSettings()
Resets the Simulator to clean state (like the Simulator > Reset Content and Settings... menu item), especially removing previously set permissions.
xcode でシミュレーターをリセットする際に実施する手順と同じ内容を実行できます。
この関数を単体で利用した場合にはテストが終了しなかったので、device.launchAppと合わせて使ってあげる必要がありそうです。
最終形としては下記になりました。
describe('example', () => {
beforeEach(async () => {
await device.resetContentAndSettings();
await device.launchApp({
delete: true,
newInstance: true,
});
});
it('test is described here', async () => {
// ...
}
});
デメリット
処理時間
この方法は、device.reloadReactNative()と比べて非常に時間がかかります。
サービスの初期画面がログイン処理で、すべてのテストの冪等性を…と考えると全テストの前にこの処理を配置することになるので処理時間は悪夢です。
ヘッドレスモード
上記の処理を使わずテストを動かしている際に、ぬるぬる動く画面を見て処理の状況を確認できました。
また、detox testコマンドは--record-videosオプションをつけると処理の動画も保存してくれます。
ですが今回、上記の処理を付加すると--record-videosオプションを使用してテストを実行できませんでした。
おわりに
テストの冪等性は非常に重要だと思います。
とはいえ、この方法だと非常にテストに時間がかかってしまうので、クレデンシャルのリセットをもう少し早くできる手法が欲しいものです。