From b2afa57ab6082792ca38435f13553500b0aaca70 Mon Sep 17 00:00:00 2001 From: Lucas Garcez Date: Thu, 31 Oct 2024 15:49:53 +1100 Subject: [PATCH] use jest.fn on mocked hooks (#449) --- README.md | 23 +++++++++++++++++++++++ jest/mock.tsx | 8 ++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 220c7c5e..c67d1bcb 100644 --- a/README.md +++ b/README.md @@ -302,6 +302,29 @@ export function TestSafeAreaProvider({ children }) { } ``` +#### Enabling Babel Parsing for Modules + +While trying to use this mock, a frequently encountered error is: + +```js +SyntaxError: Cannot use import statement outside a module. +``` + +This issue arises due to the use of the import statement. To resolve it, you need to permit Babel to parse the file. + +By default, [Jest does not parse files located within the node_modules folder](<(https://jestjs.io/docs/configuration#transformignorepatterns-arraystring)>). + +However, you can modify this behavior as outlined in the Jest documentation on [`transformIgnorePatterns` customization](https://jestjs.io/docs/tutorial-react-native#transformignorepatterns-customization). +If you're using a preset, like the one from [react-native](https://github.com/facebook/react-native/blob/main/packages/react-native/jest-preset.js), you should update your Jest configuration to include `react-native-safe-area-context` as shown below: + +```js +transformIgnorePatterns: [ + 'node_modules/(?!((jest-)?react-native|@react-native(-community)?|react-native-safe-area-context)/)', +]; +``` + +This adjustment ensures Babel correctly parses modules, avoiding the aforementioned syntax error. + ## Contributing See the [Contributing Guide](CONTRIBUTING.md) diff --git a/jest/mock.tsx b/jest/mock.tsx index ed01019f..81688c02 100644 --- a/jest/mock.tsx +++ b/jest/mock.tsx @@ -30,18 +30,18 @@ const RNSafeAreaContext = jest.requireActual<{ export default { ...RNSafeAreaContext, initialWindowMetrics: MOCK_INITIAL_METRICS, - useSafeAreaInsets: () => { + useSafeAreaInsets: jest.fn(() => { return ( useContext(RNSafeAreaContext.SafeAreaInsetsContext) ?? MOCK_INITIAL_METRICS.insets ); - }, - useSafeAreaFrame: () => { + }), + useSafeAreaFrame: jest.fn(() => { return ( useContext(RNSafeAreaContext.SafeAreaFrameContext) ?? MOCK_INITIAL_METRICS.frame ); - }, + }), // Provide a simpler implementation with default values. SafeAreaProvider: ({ children, initialMetrics }: SafeAreaProviderProps) => { return (