Skip to content

Commit

Permalink
use jest.fn on mocked hooks (#449)
Browse files Browse the repository at this point in the history
  • Loading branch information
LucasGarcez authored Oct 31, 2024
1 parent e5d23b8 commit b2afa57
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
8 changes: 4 additions & 4 deletions jest/mock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down

0 comments on commit b2afa57

Please sign in to comment.