Skip to content

Commit b2afa57

Browse files
authored
use jest.fn on mocked hooks (#449)
1 parent e5d23b8 commit b2afa57

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,29 @@ export function TestSafeAreaProvider({ children }) {
302302
}
303303
```
304304

305+
#### Enabling Babel Parsing for Modules
306+
307+
While trying to use this mock, a frequently encountered error is:
308+
309+
```js
310+
SyntaxError: Cannot use import statement outside a module.
311+
```
312+
313+
This issue arises due to the use of the import statement. To resolve it, you need to permit Babel to parse the file.
314+
315+
By default, [Jest does not parse files located within the node_modules folder](<(https://jestjs.io/docs/configuration#transformignorepatterns-arraystring)>).
316+
317+
However, you can modify this behavior as outlined in the Jest documentation on [`transformIgnorePatterns` customization](https://jestjs.io/docs/tutorial-react-native#transformignorepatterns-customization).
318+
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:
319+
320+
```js
321+
transformIgnorePatterns: [
322+
'node_modules/(?!((jest-)?react-native|@react-native(-community)?|react-native-safe-area-context)/)',
323+
];
324+
```
325+
326+
This adjustment ensures Babel correctly parses modules, avoiding the aforementioned syntax error.
327+
305328
## Contributing
306329

307330
See the [Contributing Guide](CONTRIBUTING.md)

jest/mock.tsx

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,18 +30,18 @@ const RNSafeAreaContext = jest.requireActual<{
3030
export default {
3131
...RNSafeAreaContext,
3232
initialWindowMetrics: MOCK_INITIAL_METRICS,
33-
useSafeAreaInsets: () => {
33+
useSafeAreaInsets: jest.fn(() => {
3434
return (
3535
useContext(RNSafeAreaContext.SafeAreaInsetsContext) ??
3636
MOCK_INITIAL_METRICS.insets
3737
);
38-
},
39-
useSafeAreaFrame: () => {
38+
}),
39+
useSafeAreaFrame: jest.fn(() => {
4040
return (
4141
useContext(RNSafeAreaContext.SafeAreaFrameContext) ??
4242
MOCK_INITIAL_METRICS.frame
4343
);
44-
},
44+
}),
4545
// Provide a simpler implementation with default values.
4646
SafeAreaProvider: ({ children, initialMetrics }: SafeAreaProviderProps) => {
4747
return (

0 commit comments

Comments
 (0)