Sentry-react-native: Jest fails because of sentry with error "ReferenceError: You are trying to `import` a file after the Jest environment has been torn down."

Created on 10 Oct 2019  路  3Comments  路  Source: getsentry/sentry-react-native

OS:

  • [ ] Windows
  • [x] MacOS
  • [ ] Linux

_Platform:_

  • [x] iOS
  • [ ] Android

SDK:

  • [x] @sentry/react-native
  • [ ] react-native-sentry

react-native version: 0.60.5

Hey everyone. I am trying to setup Sentry in my application. Sentry is working properly when running the app. My problem is that jest fails with "ReferenceError: You are trying to import a file after the Jest environment has been torn down." After some debugging i found that the error is caused by the line Sentry.captureMessage('Hello Sentry!');
My transformIgnorePatterns:

    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|@react-native-firebase|react-navigation|react-navigation-redux-helpers|@react-navigation|@sentry/react-native.*)"
    ],

I also tried mocking with the following:

jest.mock('@sentry/react-native', () => ({
  Sentry: {
    setTagsContext: jest.fn(),
    setExtraContext: jest.fn(),
    captureBreadcrumb: jest.fn(),
  },
}));

But this results in "TypeError: Sentry.init is not a function"

Any help is appreciated.

Steps to reproduce:

  • Create react-native project
  • Setup Sentry with default configuration
  • Run Jest test

Actual result:
Jest fails

Expected result:
Jest passes

Most helpful comment

@Coci0alex, you've probably sussed it by now but I think you just needed to remove the Sentry object wrapper in your mock, the following worked for me:

jest.mock('@sentry/react-native', () => ({
    init: jest.fn()
}));

For reference to make that mock global I put it in a setup file and configured with the following in jest.config.js :

    "setupFilesAfterEnv": [
        "<rootDir>/setup-test-env.js"
    ]

All 3 comments

I also tried putting jest.useFakeTimers() in my "App-test.js" as was suggested when i googled the reference error.

So our package doesn't provide a default export, also the functions you mocked to not exist on the Sentry object.

setTagsContext: jest.fn(),
    setExtraContext: jest.fn(),
    captureBreadcrumb: jest.fn(),

are the functions of the old SDK.

I am not

@Coci0alex, you've probably sussed it by now but I think you just needed to remove the Sentry object wrapper in your mock, the following worked for me:

jest.mock('@sentry/react-native', () => ({
    init: jest.fn()
}));

For reference to make that mock global I put it in a setup file and configured with the following in jest.config.js :

    "setupFilesAfterEnv": [
        "<rootDir>/setup-test-env.js"
    ]
Was this page helpful?
0 / 5 - 0 ratings