Created
September 13, 2022 12:51
-
-
Save 1natsu172/83313161b9429aafa8061c505bef4e87 to your computer and use it in GitHub Desktop.
React NativeのAppStateのモックのスニペット
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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