-
Notifications
You must be signed in to change notification settings - Fork 476
Error Setting Up jest.mock("@react-native-async-storage/async-storage")
#849
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Does this work with Jest 26? Afaik, react-native doesn't support Jest 29 until 0.71. |
Just tried to upgrade to 0.71-rc0, getting the same issue. We are using the setupTests approach described in the docs. ReferenceError: /__tests__/setupTests.ts: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
Invalid variable access: async_storage_mock_1
Allowed objects: AbortController, AbortSignal, AggregateError, Array, ArrayBuffer, Atomics, BigInt, BigInt64Array, BigUint64Array, Blob, Boolean, BroadcastChannel, Buffer, ByteLengthQueuingStrategy, CompressionStream, CountQueuingStrategy, Crypto, CryptoKey, CustomEvent, DOMException, DataView, Date, DecompressionStream, Error, EvalError, Event, EventTarget, FinalizationRegistry, Float32Array, Float64Array, FormData, Function, Generator, GeneratorFunction, Headers, Infinity, Int16Array, Int32Array, Int8Array, InternalError, Intl, JSON, Map, Math, MessageChannel, MessageEvent, MessagePort, NaN, Number, Object, Performance, PerformanceEntry, PerformanceMark, PerformanceMeasure, PerformanceObserver, PerformanceObserverEntryList, PerformanceResourceTiming, Promise, Proxy, RangeError, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, ReferenceError, Reflect, RegExp, Request, Response, Set, SharedArrayBuffer, String, SubtleCrypto, Symbol, SyntaxError, TextDecoder, TextDecoderStream, TextEncoder, TextEncoderStream, TransformStream, TransformStreamDefaultController, TypeError, URIError, URL, URLSearchParams, Uint16Array, Uint32Array, Uint8Array, Uint8ClampedArray, WeakMap, WeakRef, WeakSet, WebAssembly, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter, __dirname, __filename, arguments, atob, btoa, clearImmediate, clearInterval, clearTimeout, console, crypto, decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, escape, eval, expect, exports, fetch, global, globalThis, isFinite, isNaN, jest, module, parseFloat, parseInt, performance, process, queueMicrotask, require, setImmediate, setInterval, setTimeout, structuredClone, undefined, unescape.
Note: This is a precaution to guard against uninitialized mock variables. If it is ensured that the mock is required lazily, variable names prefixed with `mock` (case insensitive) are permitted.
4 | };
5 | Object.defineProperty(exports, "__esModule", { value: true });
> 6 | jest.mock('@react-native-async-storage/async-storage', () => async_storage_mock_1.default);
| ^^^^^^^^^^^^^^^^^^^^ |
I don't know if this is new with Jest 29, but if you do a diff --git a/test/setup.ts b/test/setup.ts
index 63b666c..7fefe9d 100644
--- a/test/setup.ts
+++ b/test/setup.ts
@@ -1,6 +1,5 @@
// we always make sure 'react-native' gets included first
import * as ReactNative from "react-native"
-import mockAsyncStorage from "@react-native-async-storage/async-storage/jest/async-storage-mock"
import mockFile from "./mockFile"
// libraries to mock
@@ -24,7 +23,9 @@ jest.doMock("react-native", () => {
)
})
-jest.mock("@react-native-async-storage/async-storage", () => mockAsyncStorage)
+jest.mock("@react-native-async-storage/async-storage", () =>
+ require("@react-native-async-storage/async-storage/jest/async-storage-mock"),
+)
jest.mock("i18n-js", () => ({
currentLocale: () => "en", @krizzu: Do you know anything about this? Do we need to update the docs? |
@varemenos Can you show your jest config file? If @tido64 solution works, I think we should update the docs. I think I saw this issue when using
I wonder if changing the name to |
I tried the inline require but it didn't seem to have any effect. You are correct in assuming that I'm using ts-jest, here is my eslint config file: module.exports = {
preset: 'react-native',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
setupFiles: ['./__tests__/setupTests.ts'],
setupFilesAfterEnv: ['@testing-library/jest-native/extend-expect'],
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
testMatch: ['**/__tests__/*.spec.(js|jsx|ts|tsx)'],
transformIgnorePatterns: [
'/node_modules/(?!react-native)/.+',
'\\.snap$',
'jest-runner',
],
cacheDirectory: '.jest/cache',
transform: {
'^.+\\.jsx$': 'babel-jest',
'^.+\\.tsx?$': [
'ts-jest',
{
tsconfig: 'tsconfig.spec.json',
babelConfig: 'babel.config.js',
diagnostics: false,
isolatedModules: true,
},
],
},
} I was also experiencing the "private method error", but I just made module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: ['react-native-reanimated/plugin'],
env: { production: { plugins: ['transform-remove-console'] } },
} // tsconfig.json
{
"extends": "@tsconfig/react-native/tsconfig.json",
"compilerOptions": {
"typeRoots": ["node_modules/@types", "lib/typings"],
"skipLibCheck": true
}
}
// tsconfig.spec.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"jsx": "react"
}
} This is most likely irrelevant to the issue but the current package json for async storage has the following range. Which I assume will need to change when RN 0.71 lands.
|
@varemenos: What's the content of your |
A bunch of overrides/mocks import { Image } from 'react-native'
Image.getSize = jest.fn()
import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock'
jest.mock('@react-native-async-storage/async-storage', () => mockAsyncStorage)
import mockRNCNetInfo from '@react-native-community/netinfo/jest/netinfo-mock.js'
import mockClipboard from '@react-native-clipboard/clipboard/jest/clipboard-mock.js'
import mockRNGestureHandler from 'react-native-gesture-handler/jestSetup.js'
jest.mock('react-native-gesture-handler', () => mockRNGestureHandler)
jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper')
jest.mock('@react-native-community/netinfo', () => mockRNCNetInfo)
jest.mock('@react-native-clipboard/clipboard', () => mockClipboard)
global.__DEV__ = true
global.ReanimatedDataMock = { now: () => 0 }
global.__reanimatedWorkletInit = jest.fn()
jest.mock('../lib/config', () => ({
BASE_URL: 'localhost:3000',
})) |
Right, this is the file where you would substitute the import for an inline require. Can you try that and report back? |
Ya, that's where I changed the snippet you sent earlier. This is far fetched but is there a chance the removal of AsyncStorage from RN in 0.71 could somehow indirectly affect this? (or it's existence somehow prevented the problem from surfacing?) |
Do you still get this exact error after the change? I find that peculiar because we are doing exactly what the error message tells us to. |
No actually you are 100% right, the root cause of the issue doesn't seem related to AsyncStorage after all. Since when I did what you recommended and replace the import with an inline require, the next library that I mocked had the same exception (which I was careless enough not to notice until you asked me to double-check). So I replaced all of them with inline requires, and now the issue has gone away. |
Thanks for checking. I've updated the docs. |
🎉 This issue has been resolved in version 1.17.11 🎉 The release is available on: Your semantic-release bot 📦🚀 |
What happened?
I just upgraded my dependencies and now I get the following error during my setup when running
jest
:Moving the mock into the
__mocks__
folder or changing it tojest.doMock(...)
fixes the error but then times out on the tests consumingAsyncStorage
.Version
1.17.10
What platforms are you seeing this issue on?
System Information
Steps to Reproduce
I uploaded a repo that reproduces the issue here to make things quicker: https://github.com/Silthus/jest-async-storage-error
Just clone it and run
yarn install
thenyarn test
to reproduce the error.The repo was created the following way:
npx ignite-cli new JestDemo \ --bundle=test.jest \ --git \ --install-deps \ --packager=yarn \ --target-path=C:\temp\jest-demo\JestDemo \ --remove-demo
android
andios
folders.yarn upgrade-interactive --latest -E
and upgrade all dependencies to the latest version.jest-environment-jsdom
:yarn add --dev jest-environment-jsdom
@babel/plugin-proposal-private-methods
tobabel.config.js
yarn test
and see the tests failThe text was updated successfully, but these errors were encountered: