Skip to content

Instantly share code, notes, and snippets.

@1natsu172
Created September 13, 2022 12:51
Show Gist options
  • Save 1natsu172/83313161b9429aafa8061c505bef4e87 to your computer and use it in GitHub Desktop.
Save 1natsu172/83313161b9429aafa8061c505bef4e87 to your computer and use it in GitHub Desktop.
React NativeのAppStateのモックのスニペット
import { renderHook, act } from '@testing-library/react-hooks'
import { AppState, AppStateStatus } from 'react-native'
let appStateAddEventListenerHandlerMock: (
nextAppStateStatus: AppStateStatus,
) => void
// NOTE: fetchをモックしておくためにglobalに型を生やす
type FetchMock = NodeJS.Global & {
fetch: unknown
}
beforeEach(() => {
jest.clearAllMocks()
// fetchをモックしておく
;(global as FetchMock).fetch = jest.fn()
// AppStateをモックしておく
jest.mock('react-native/Libraries/AppState/AppState', () => ({
addEventListener: jest.fn(
(_event: string, fn: (nextAppStateStatus: AppStateStatus) => unknown) => {
// NOTE: テスト上、任意のタイミングでイベントタイプを添えてハンドラを発火できるようにモックを変数に格納しておく
appStateAddEventListenerHandlerMock = (
nextAppStateStatus: AppStateStatus,
) => {
fn(nextAppStateStatus)
}
},
),
removeEventListener: jest.fn(
(_event: string, fn: (nextAppStateStatus: AppStateStatus) => unknown) => {
return (nextAppStateStatus: AppStateStatus) => {
fn(nextAppStateStatus)
}
},
),
}))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment