Skip to content

Instantly share code, notes, and snippets.

@vovkasm
Created January 10, 2019 10:06
Show Gist options
  • Save vovkasm/a4a720cc1d4eb8bceb8daa778ac7036a to your computer and use it in GitHub Desktop.
Save vovkasm/a4a720cc1d4eb8bceb8daa778ac7036a to your computer and use it in GitHub Desktop.
Jest + react-native mock native modules
// Tune promises (we use Bluebird, but with setImmediate instead of nextTick etc optimizations...)
// It will allow to us call jest.runAllImmediates() to force promises queue flush
global.Promise = require('App/promise').default
global.Promise.setScheduler(function(fn) {
setImmediate(fn)
})
jest.mock('NativeEventEmitter')
const NativeModules = {
RNFirebase: {
apps: [{ name: '[DEFAULT]' }, { name: 'notifications' }, { name: 'messaging' }],
},
RNFirebaseAnalytics: {
setUserId: jest.fn(),
},
RNFirebaseMessaging: {
jsInitialised: jest.fn(() => Promise.resolve()),
getToken: jest.fn(() => Promise.resolve('FIREBASE_TOKEN')),
},
RNFirebaseNotifications: {
jsInitialised: jest.fn(() => Promise.resolve()),
getInitialNotification: jest.fn(() => Promise.resolve()),
},
RNFSManager: {
RNFSMainBundlePath: 'main-bundle',
RNFSCachesDirectoryPath: 'caches',
RNFSDocumentDirectoryPath: 'documents',
RNFSExternalDirectoryPath: 'external',
RNFSExternalStorageDirectoryPath: 'external-storage',
RNFSTemporaryDirectoryPath: 'tmp',
RNFSLibraryDirectoryPath: 'library',
RNFSFileTypeRegular: 'file-type-regular',
RNFSFileTypeDirectory: 'file-type-directory',
},
RNShare: {},
OurLocation: {
getLocation: jest.fn().mockResolvedValue({ coords: { latitude: 55, longitude: 37 } }),
requestAuthorization: jest.fn(() => Promise.resolve()),
},
OurNavigator: {
present: jest.fn(() => Promise.resolve()),
dismiss: jest.fn(() => Promise.resolve()),
push: jest.fn(() => Promise.resolve()),
pop: jest.fn(() => Promise.resolve()),
},
}
Object.keys(NativeModules).forEach((name) => {
mockReactNativeModule(name, NativeModules[name])
})
function mockReactNativeModule(name, shape) {
jest.doMock(name, () => shape, { virtual: true })
require('react-native').NativeModules[name] = shape
}
@honia19
Copy link

honia19 commented Feb 11, 2021

the best solution ever! Thanks!

@danielwinkler
Copy link

works like a charm!

@Mr0cket
Copy link

Mr0cket commented May 6, 2022

How do I use this setup?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment