react-native-firebase icon indicating copy to clipboard operation
react-native-firebase copied to clipboard

[Question] How i can test my functions with jest?

Open approached opened this issue 6 years ago • 32 comments

Hi@all,

How i can test my functions with jest? I become follow error:

 FAIL  src/data/auth/__test__/register.test.js
  ● Test suite failed to run

    /Users/approach/workspace/TakeActive/node_modules/@react-native-firebase/analytics/lib/index.js:18
    import {
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import analytics from "@react-native-firebase/analytics";
        | ^

My jest.config.js

module.exports = {
  roots: ['src'],
};

Has anybody a idea? In the documentation i don't found help.


Think react-native-firebase is great? Please consider supporting all of the project maintainers and contributors by donating via our Open Collective where all contributors can submit expenses. [Learn More]

approached avatar Dec 23 '19 17:12 approached

I am having a similar problem with imports.

` import { getFirebaseRoot } from './internal/registry/namespace';

SyntaxError: Cannot use import statement outside a module

> 1 | import firebase from '@react-native-firebase/app';
    | ^
  2 | import '@react-native-firebase/firestore';
  3 | import '@react-native-firebase/crashlytics';`

tattivitorino avatar Jan 06 '20 18:01 tattivitorino

Add it to transformIgnorePattern perhaps - I'm still on v5 but I imagine I'll have to add it as an extra entry in the 'or' part of the pattern match like this

(base) mike@kunashir:~/work/Kullki/ksocialscore/packages/public-app (onboarding) % more jest.config.js 
module.exports = {
  rootDir: './dist/tests/rnapp/js',
  roots: ['<rootDir>'],
  // transform: {
  //   '^.+\\.tsx?$': 'ts-jest',
  // },
  transformIgnorePatterns: [
    'node_modules/(?!@react-native-community/google-signin|react-native|reactxp-webview|react-pose-core|animated-pose|@react-native-community/async-storage|@invertase/react-native-apple-authentication)',
  ],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  preset: 'react-native',
  testEnvironment: 'jsdom',
  collectCoverage: true,
  setupFilesAfterEnv: [
    './__mocks__/mockFirebase.js',
    './__mocks__/mockReactNative.js',
    './__mocks__/mockAsyncStorage.js',
  ],
};
// module.exports = {
//  testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
// };

mikehardy avatar Jan 06 '20 18:01 mikehardy

@mikehardy I have a transformIgnorePattern setup like below in the package.json and I'm on v6

{
  "scripts": {
    "postinstall": "jetify",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "web": "expo start --web",
    "start": "react-native start",
    "test": "jest"
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.7.1",
    "@react-native-firebase/app": "^6.2.0",
    "@react-native-firebase/auth": "^6.2.0",
    "@react-native-firebase/crashlytics": "^6.2.0",
    "@react-native-firebase/firestore": "^6.2.0",
    "expo": "~36.0.0",
    "expo-asset": "^8.0.0",
    "expo-font": "^8.0.0",
    "expo-linear-gradient": "^8.0.0",
    "expo-location": "^8.0.0",
    "expo-permissions": "^8.0.0",
    "formik": "^2.0.8",
    "geofirestore": "^3.3.1",
    "geolib": "^3.2.0",
    "haversine": "^1.1.1",
    "js-sha256": "^0.9.0",
    "lodash": "^4.17.15",
    "moment": "^2.24.0",
    "moment-duration-format": "^2.3.2",
    "native-base": "^2.13.8",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "~0.61.4",
    "react-native-base64": "^0.0.2",
    "react-native-dotenv": "^0.2.0",
    "react-native-elements": "^1.2.7",
    "react-native-gesture-handler": "~1.5.0",
    "react-native-keyboard-aware-scroll-view": "^0.9.1",
    "react-native-maps": "^0.26.1",
    "react-native-maps-animated-polyline": "^1.0.6",
    "react-native-maps-super-cluster": "^1.6.0",
    "react-native-reanimated": "~1.4.0",
    "react-native-safe-area-context": "0.6.0",
    "react-native-safe-area-view": "^1.0.0",
    "react-native-scalable-image": "^1.0.0",
    "react-native-screens": "~2.0.0-alpha.12",
    "react-native-splash-screen": "^3.2.0",
    "react-native-svg": "^9.13.6",
    "react-native-unimodules": "~0.7.0",
    "react-native-web": "~0.11.7",
    "react-navigation": "^4.0.10",
    "react-navigation-drawer": "^2.2.2",
    "react-navigation-header-buttons": "^3.0.4",
    "react-navigation-stack": "^1.9.4",
    "react-navigation-tabs": "^2.5.6",
    "react-redux": "^7.1.1",
    "redux": "^4.0.4",
    "redux-thunk": "^2.3.0",
    "reselect": "^4.0.0",
    "throttle-debounce": "^2.1.0"
  },
  "devDependencies": {
    "@babel/core": "~7.6.0",
    "babel-jest": "~24.9.0",
    "jest": "~24.9.0",
    "jest-expo": "^36.0.0",
    "jetifier": "~1.6.4",
    "metro-react-native-babel-preset": "~0.56.0",
    "react-native-svg-transformer": "^0.14.3",
    "react-test-renderer": "~16.9.0",
    "redux-devtools-extension": "^2.13.8"
  },
  "jest": {
    "projects": [
      {
        "preset": "jest-expo/ios"
      },
      {
        "preset": "jest-expo/android"
      }
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|@react-native-firebase/app)"
    ]
  },
  "private": true
}

tattivitorino avatar Jan 06 '20 18:01 tattivitorino

why just @react-native-firebase/app? Try all @react-native-firebase maybe

mikehardy avatar Jan 06 '20 18:01 mikehardy

@mikehardy I tried @react-native-firebase and @react-native-firebase/.* and still having the same error! :( I must say I am new to Jest testing so I'm quite lost in the middle of so many configs.

and thanks a lot for taking the time to try and help

tattivitorino avatar Jan 06 '20 19:01 tattivitorino

Well I have the same problem. Do anyone have a solution?

Shaquu avatar Jan 12 '20 23:01 Shaquu

Hello 👋, to help manage issues we automatically close stale issues. This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Feb 10 '20 00:02 stale[bot]

I still have the same problem. Any updates? Please don't close this

midal avatar Feb 14 '20 10:02 midal

I also have this problem, and couldn't solve it with the suggested transformIgnorePattern's...

anfriis avatar Feb 27 '20 15:02 anfriis

I added my transformIgnorePattern to my jest.config.js instead which was overriding the setting in package.json. Now I get this issue instead:

 Invariant Violation: Native module cannot be null.

      at invariant (node_modules/invariant/invariant.js:40:15)
      at RNFBNativeEventEmitter.NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:36:7)
      at new RNFBNativeEventEmitter (node_modules/@react-native-firebase/app/lib/internal/RNFBNativeEventEmitter.js:24:5)
      at Object.<anonymous> (node_modules/@react-native-firebase/app/lib/internal/RNFBNativeEventEmitter.js:48:16)
      at Object.<anonymous> (node_modules/@react-native-firebase/app/lib/internal/registry/nativeModule.js:21:1)

Looking around similar issues it seems like it can be mocked - just gotta figure out how.

anfriis avatar Feb 27 '20 15:02 anfriis

I'm also on v6 and Crashlytics were causing the issue in my case but managed to solve it. To solve the before mentioned Invariant Violation issue, I added a crashlytics.js file in this folder structure: <rootDir>/jest/mocks/firebase/crashlytics.js:

export default () => ({
    log: message => {},
    recordError: err => {},
})

And added the following to my jest.config.js:

moduleNameMapper: {
    '@react-native-firebase/crashlytics': '<rootDir>/jest/mocks/firebase/crashlytics.js',
}

I actually didn't need the transformIgnorePattern in the jest.config.js to make it work. @mikehardy @approached

anfriis avatar Feb 28 '20 09:02 anfriis

This worked for me. You can try to use jest.mock() right above the first import in your test file like this:

jest.mock('../location_of_your_module', () => {
    return () => ({
      function_that_you_want_to_mock: jest.fn(),
      ....
     });
});

LorandP avatar Mar 25 '20 14:03 LorandP

Hello 👋, to help manage issues we automatically close stale issues. This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Apr 23 '20 04:04 stale[bot]

Facing the same problem with v6 even though I've tried the suggested workarounds. Any thoughts ?

januarioprime avatar May 05 '20 06:05 januarioprime

@januarioprime to fix the problem:

Create a __mocks__ folder at the root of your project, and add the mocked modules you are using there. For instance:

// __mocks__/@react-native-firebase/app.js

export default () => ({
  currentUser: { idToken: 'mocked-id-token' },
});

// __mocks__/@react-native-firebase/auth.js

export default () => ({
  signInWithEmailAndPassword: jest.fn(),
  createUserWithEmailAndPassword: jest.fn(),
  signOut: jest.fn(),
  sendPasswordResetEmail: jest.fn(),
});

For me it has solved the problem.

PierreCapo avatar May 14 '20 16:05 PierreCapo

Hey all,

We use jest testing now on this mono-repo; our config file can be seen here: https://github.com/invertase/react-native-firebase/blob/master/jest.config.js

To get JS imports working correctly; the transform ignore pattern @mikehardy mentioned above is probably the way to go.

In terms of mocking you could do this via a jest setup file;

module.exports = {
  // ...
  setupFiles: ['./jest.setup.ts'],
  // ...
};

For our current testing cases this is what we've done in our jest.setup.ts file: https://github.com/invertase/react-native-firebase/blob/master/jest.setup.ts - this doesn't cover all native modules - you'll need to add additional ones that you're using.

Hopefully this helps.

Salakar avatar May 15 '20 11:05 Salakar

Well @mikehardy told me that i cannot laught, so i show my problem here.

Im still facing the issue Have in my package.json

    "@react-native-firebase/app": "^6.7.1",
    "@react-native-firebase/crashlytics": "^6.7.1",
    "@react-native-firebase/database": "^6.7.1",
    "@react-native-firebase/messaging": "^6.7.1",

in my setup-jest.js

jest.mock('@react-native-firebase/app');

jest.mock('react-native-notifications');

jest.mock('@react-native-firebase/database');

jest.mock('@react-native-firebase/crashlytics', () => () => ({
  recordError: jest.fn(),
  logEvent: jest.fn(),
  setUserProperties: jest.fn(),
  setUserId: jest.fn(),
  setCurrentScreen: jest.fn(),
}));


jest.mock('@react-native-firebase/messaging', () => () => ({
  hasPermission: jest.fn(() => Promise.resolve(true)),
  subscribeToTopic: jest.fn(),
  unsubscribeFromTopic: jest.fn(),
  requestPermission: jest.fn(() => Promise.resolve(true)),
  getToken: jest.fn(() => Promise.resolve('myMockToken')),
  onTokenRefresh: jest.fn((callback) => callback(Promise.resolve('Example'))),
}));

But im still getting

  ● Test suite failed to run

    Invariant Violation: Native module cannot be null.

      at invariant (node_modules/invariant/invariant.js:40:15)
      at RNFBNativeEventEmitter.invariant (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:36:7)
      at new RNFBNativeEventEmitter (node_modules/@react-native-firebase/app/lib/internal/RNFBNativeEventEmitter.js:24:5)
      at Object.<anonymous> (node_modules/@react-native-firebase/app/lib/internal/RNFBNativeEventEmitter.js:48:16)
      at Object.<anonymous> (node_modules/@react-native-firebase/app/lib/internal/registry/nativeModule.js:21:1)

Idk what more mock

ccanalesb avatar May 15 '20 20:05 ccanalesb

I dunno, laughing while helping is a great combo. May be something missing still @Salakar how would you stub out the native emitter stuff? Why is that even being called in a jest environment (are there events to emit?)

mikehardy avatar May 15 '20 20:05 mikehardy

My friend @JulioOrellana find the solution to my problem

It was necesary create a mock file for every lib used

 __mocks__/@react-native-firebase/app.js         
 __mocks__/@react-native-firebase/crashlytics.js 
 __mocks__/@react-native-firebase/database.js    
 __mocks__/@react-native-firebase/messaging.js 
 __mocks__/react-native-notifications.js 

And in each of those file make the correct export Idk if was a misconfiguration before, but mock in setup-test.js will not work for me

ccanalesb avatar May 15 '20 20:05 ccanalesb

I linked above what you need to mock for Native modules e.g. the event emitter; https://github.com/invertase/react-native-firebase/blob/master/jest.setup.ts

If you mock the underlying react native native modules rather than the RNFB packages themselves you'll have a much better/accurate mock - or at least in our testing for RNFB itself that was the best way.

Salakar avatar May 18 '20 10:05 Salakar