Created
January 10, 2019 10:06
-
-
Save vovkasm/a4a720cc1d4eb8bceb8daa778ac7036a to your computer and use it in GitHub Desktop.
Jest + react-native mock native modules
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
works like a charm!
How do I use this setup?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
the best solution ever! Thanks!