Jest测试Expo应用Firestore时setDoc卡住超时
Expo应用Firestore测试超时问题
我用jest配合Firebase模拟器测试Expo应用的Firestore实现,但执行测试时总是卡在setDoc步骤不返回,最终导致超时。
试过两种方式:
- 用
firebase-admin时,能看到数据已经写入Firestore模拟器,但setDoc始终不返回; - 用普通firebase SDK的话,完全没法写入数据。
测试环境用的是jsdom,也试过jest-environment-jsdom,都没用。已经确认Firebase模拟器在8080端口正常运行。
测试代码(App.test.ts)
import {initializeApp} from 'firebase/app'; import {collection, connectFirestoreEmulator, doc, getFirestore, setDoc} from 'firebase/firestore'; import {API_KEY, APP_ID, AUTH_DOMAIN, MEASUREMENT_ID, MESSAGING_SENDER_ID, PROJECT_ID, STORAGE_BUCKET} from '@env'; const firebaseConfig = { apiKey: API_KEY, authDomain: AUTH_DOMAIN, projectId: PROJECT_ID, storageBucket: STORAGE_BUCKET, messagingSenderId: MESSAGING_SENDER_ID, appId: APP_ID, measurementId: MEASUREMENT_ID, }; describe('Firebase', () => { jest.setTimeout(30000) it('should initialize Firebase', async () => { const app = initializeApp(firebaseConfig); const db = getFirestore(app); connectFirestoreEmulator(db, 'localhost', 8080) await setDoc(doc(db, "cities", "LA"), { name: "Los Angeles", state: "CA", country: "USA" }); }); });
Jest配置(jest.config.ts)
const config: JestConfigWithTsJest = { ...tsjPreset, verbose: true, testEnvironment: 'jest-environment-jsdom', preset: 'jest-expo', setupFiles: ['./jest_setup/asyncStorage.ts'], extensionsToTreatAsEsm: ['.ts', '.tsx'], moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1', }, transform: { '^.+\\.tsx?$': [ 'ts-jest', { useESM: true, tsconfig: 'tsconfig.spec.json', babelConfig: 'babel.config.js' }, ], }, testMatch: [ '**/?(*.)+(spec|test).ts?(x)', ], collectCoverageFrom: [ '**/*.{ts,tsx}', '!**/coverage/**', '!**/node_modules/**', '!**/babel.config.js', '!**/jest.setup.js', ], moduleFileExtensions: [ 'js', 'ts', 'tsx', ], transformIgnorePatterns: [ 'node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg|@react-navigation/native-stack|@firebase|firebase/.*|@react-native|react-native)', ], coverageReporters: [ 'json-summary', 'text', 'lcov', ], };
开发依赖(package.json片段)
"devDependencies": { "@babel/core": "^7.22.1", "@babel/preset-env": "^7.22.4", "@babel/preset-typescript": "^7.21.5", "@jest/globals": "^29.5.0", "@types/jest": "^29.5.2", "@types/react": "~18.0.27", "@types/react-dom": "~18.0.10", "@types/react-native": "^0.72.2", "@types/react-test-renderer": "^18.0.0", "@types/validator": "^13.7.17", "babel-jest": "^29.5.0", "babel-plugin-module-resolver": "^5.0.0", "deprecated-react-native-prop-types": "^4.1.0", "jest": "^29.5.0", "jest-environment-jsdom": "^29.5.0", "jest-expo": "^48.0.2", "react-native-dotenv": "^3.4.8", "ts-jest": "^29.1.0", "typescript": "^4.9.4" },
内容的提问来源于stack exchange,提问作者Chongju Mai
相关产品推荐
相关产品推荐

