使用initializeTestApp时报错firebase__default.default.initializeApp is not a function
问题根因
该报错是ES模块与CommonJS模块互操作导致的导入异常,你使用的@firebase/rules-unit-testing 1.x版本没有默认导出,转译过程中错误将方法挂载到了default属性下,所以调用对应方法时找不到定义。
解决方案
- 调整导入语法,不要用
import * as firebase的写法,直接按需导入所需方法:
// 修改导入部分 import { initializeTestApp, clearFirestoreData, loadFirestoreRules, assertFails } from "@firebase/rules-unit-testing"; import fs from "fs"; import path from "path";
对应方法调用不需要再带firebase.前缀,修改后的测试代码参考:
const myId = "user_Id"; // Load security rules const filePath = path.join(__dirname, "./firestore.rules"); const rules = fs.readFileSync(filePath, "utf8"); const myProjectId = "my-project-2021"; describe("Allow access to users collection only when user is authorized", () => { beforeEach( async () => await clearFirestoreData({ projectId: myProjectId }) ); beforeEach( async () => await loadFirestoreRules({ projectId: myProjectId, rules: rules, }) ); afterAll( async () => await clearFirestoreData({ projectId: myProjectId }) ); describe("allow access to project collection only when user is authorized", () => { test("fail to access without auth", async () => { const db = initializeTestApp({ projectId: myProjectId, }) .firestore(); const doc = db .collection("users") .doc("user_shogo") .collection("projects") .doc("testProjectId"); await assertFails(doc.get()); }); }); });
- 检查
tsconfig.json配置,确保开启以下两个配置项:
{ "compilerOptions": { "esModuleInterop": true, "allowSyntheticDefaultImports": true } }
- 确认jest配置正确,使用
ts-jest预设处理TypeScript文件,jest.config.js参考配置:
module.exports = { preset: 'ts-jest', testEnvironment: 'node', moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'], transform: { '^.+\\.tsx?$': 'ts-jest' } };
操作完所有步骤后如果仍存在异常,可以删除node_modules目录后重新执行yarn install安装依赖,排除缓存问题。
内容的提问来源于stack exchange,提问作者shogo_nakano
相关产品推荐
相关产品推荐

