【问题标题】:firebase.storage() is not a function in jest test casesfirebase.storage() 不是开玩笑测试用例中的函数
【发布时间】:2017-10-20 20:38:55
【问题描述】:

我正在使用 Jest 来测试我的 firebase 功能。这一切都在浏览器中,所以我与服务器端的firebase没有任何冲突。当我使用firebase.auth()firebase.database() 时,一切正常。当我尝试使用 firebase.storage() 时,我的测试失败了。

这是我的 firebase 导入和初始化:

import firebase from 'firebase';
import config from '../config';

export const firebaseApp = firebase.initializeApp(config.FIREBASE_CONFIG);
export const firebaseAuth = firebaseApp.auth();
export const firebaseDb = firebaseApp.database();

我有一个包含上传功能的 imageUtils 文件:

import { firebaseApp } from './firebase';

export const uploadImage = (firebaseStoragePath, imageURL) => {
  return new Promise((resolve, reject) => {
    // reject if there is no imagePath provided
    if (!firebaseStoragePath) reject('No image path was provided. Cannot upload the file.');

    // reject if there is no imageURL provided
    if (!imageURL) reject('No image url was provided. Cannot upload the file');

    // create the reference
    const imageRef = firebaseApp.storage().ref().child(firebaseStoragePath);

    let uploadTask;
    // check if this is a dataURL
    if (isDataURL(imageURL)) {
      // the image is a base64 image string
      // create the upload task
      uploadTask = imageRef.putString(imageURL);
    } else {
      // the image is a file
      // create the upload task
      uploadTask = imageRef.put(imageURL);
    }

    // monitor the upload process for state changes
    const unsub = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
      (snapshot) => {
        // this is where we can check on progress
      }, (error) => {
        reject(error.serverResponse);
        unsub();
      }, () => {
        // success function
        resolve(uploadTask.snapshot.downloadURL);
        unsub();
      });
  });
};

我正在尝试为该函数创建一个测试用例,每次它失败时:

TypeError: _firebase3.firebaseApp.storage is not a function

当我正常运行应用程序时,一切正常,而且我从来没有收到关于 storage() 未定义或不是函数的错误。只有当我尝试运行测试用例时。

我在 firebase 导入中设置了 console.dir(firebaseApp); 行,它返回了 auth()database() 但没有存储空间。如何让存储正确导入/初始化/存在?

【问题讨论】:

  • 我不这么认为。那是指nodejs上的firebase,我严格在浏览器中使用它。根据 firebase 文档,从浏览器调用存储仍然是受支持的用例。

标签: javascript firebase firebase-authentication firebase-storage jestjs


【解决方案1】:

添加以下导入

import "firebase/storage";

【讨论】:

  • 在我的测试中导入firebase/storage?还是在我的 storageRef 的初始化中导入和使用?
  • 将其导入到您的初始化或 storageRef 声明中,我发现这也修复了我的测试。但是,Firebase 会提供与日期相关的警告
  • 哇,谢谢!你为我节省了很多时间。
【解决方案2】:

看起来这已在 recent update to the firebase javascript package 中修复:

【讨论】:

  • 这只是在 5.0.4 中发生在我身上。 hsc 的回答仍然修复了它。
【解决方案3】:

我遇到了同样的问题。另一种可能的解决方案:

import * as firebase from "firebase";
import "firebase/app";
import "firebase/storage";

【讨论】:

    猜你喜欢
    • 2020-08-24
    • 2017-02-11
    • 2021-09-13
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 2021-02-26
    相关资源
    最近更新 更多