Add types to "__mocks__/BackHandler.js"
See original GitHub issueDescription
Today when we need to mock the Android back press, the only way I found is using the Libraries/Utilities/__mocks__/BackHandler.js file, and then:
jest.mock(
'react-native/Libraries/Utilities/BackHandler',
() => require('react-native/Libraries/Utilities/__mocks__/BackHandler'),
);
However, when using TypeScript we get an error:
// my-test.spec.tsx
import { BackHandler } from 'react-native';
describe('My test', () => {
it('BackHandler', () => {
BackHandler.mockPressBack();
// Error: Property 'mockPressBack' does not exist on type 'BackHandlerStatic'.ts(2339)
});
});
My workaround is to create a react-native.d.ts file with:
import 'react-native';
declare module 'react-native' {
interface BackHandlerStatic {
mockPressBack(): void;
}
}
Version
0.68.2
Output of npx react-native info
System: OS: macOS 12.3.1 CPU: (8) arm64 Apple M1 Memory: 173.70 MB / 8.00 GB Shell: 5.8 - /bin/zsh Binaries: Node: 16.16.0 - ~/.nvm/versions/node/v16.16.0/bin/node Yarn: 1.22.19 - ~/.nvm/versions/node/v16.16.0/bin/yarn npm: 8.11.0 - ~/.nvm/versions/node/v16.16.0/bin/npm Watchman: 2022.05.16.00 - /opt/homebrew/bin/watchman Managers: CocoaPods: 1.11.2 - /Users/douglas.junior/.rbenv/shims/pod SDKs: iOS SDK: Platforms: DriverKit 21.4, iOS 15.4, macOS 12.3, tvOS 15.4, watchOS 8.5 Android SDK: Not Found IDEs: Android Studio: 2021.1 AI-211.7628.21.2111.8139111 Xcode: 13.3.1/13E500a - /usr/bin/xcodebuild Languages: Java: 11.0.12 - /opt/homebrew/opt/openjdk@11/bin/javac npmPackages: @react-native-community/cli: Not Found react: 17.0.2 => 17.0.2 react-native: 0.68.2 => 0.68.2 react-native-macos: Not Found npmGlobalPackages: react-native: Not Found
Steps to reproduce
Just create a new React Native project with TypeScript and try to create a mock for BackHandler.
Snack, code example, screenshot, or link to a repository
N/A
Issue Analytics
- State:
- Created a year ago
- Comments:6 (3 by maintainers)

Top Related StackOverflow Question
I see, so: You are basically trying to test what happens in your code when backHandler’s backPress is invoked right? You don’t really need BackHandler’s implementation for that. You can very easily mock BackHandler, like this I think:
What this essentially does is that we create a mock of BackHandler which, when
mockBackPressis called, invokes thehandleDismissmethod.this should work fine with your code @douglasjunior . Let me know if this helps
Make sure you pass
handleDismissMockashandleDismisswhen renderingModalI’m creating a
Modalcomponent that need to close when the “back button” was pressed.So, in my tests I do:
Inside
ModalI have:Everything is working, except for the
BackHandler.mockPressBack()type.