GithubHelp home page GithubHelp logo

firebase-mock's People

Contributors

a-xin avatar adrianosmond avatar alexlouden avatar andrei-e-random avatar andrewkvalheim avatar bendrucker avatar boyko avatar brianchapman avatar dmurvihill avatar fredyc avatar hadson19 avatar heygambo avatar huafu avatar ilearnio avatar jamestalmage avatar joshag avatar jqrgen avatar katowulf avatar lewchuk-inkling avatar mwq27 avatar op avatar raman-nbg avatar rbokel avatar redmega avatar rhodgkins avatar soumak77 avatar squirly avatar venryx avatar yearofthedan avatar zeevl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-mock's Issues

Auth::createUser* return different shape data than Firebase Web SDK

It seems like firebase-mock may be providing the wrong shape of return data for the suite of createUser* functions (or I'm misusing firebase-mock ๐Ÿ˜…) The difference is that firebase-mock is returning something that resembles firebase.User or firebase.UserInfo instead of firebase.auth.UserCredential.

I believe it should be returning data shaped like UserCredential, which has the UserInfo nested inside a user member.

Here are the relevant types from Firebase Auth (from the JS SDK).

    createUserWithEmailAndPassword(
      email: string,
      password: string
    ): Promise<firebase.auth.UserCredential>;

...where firebase.auth.UserCredential has the following shape:

  type UserCredential = {
    additionalUserInfo?: firebase.auth.AdditionalUserInfo | null;
    credential: firebase.auth.AuthCredential | null;
    operationType?: string | null;
    user: firebase.User | null;
  };

https://github.com/firebase/firebase-js-sdk/blob/master/packages/auth-types/index.d.ts#L314

Clear, reset or erase Firestore database in each test

I have posted to this issue in the old repository, but it seems like we moved to this repository so I might as well post here, sorry about that I didn't know issues should be moved to this one.

I have been trying to reset my firestore database so my tests don't have remaining data from past tests, I have found some resources in the issue linked above but I can't seem to get the database reset even after making the reassignment of the firestore variable.

jest.mock('../init', () => {
  const firebasemock = require('firebase-mock');

  let mockauth = new firebasemock.MockAuthentication();
  let mockstorage = new firebasemock.MockStorage();
  let mockfirestore = new firebasemock.MockFirestore();
  mockfirestore.autoFlush();

  return {
    reset: function() {
      const mockAut = new firebasemock.MockAuthentication();
      const mockStor = new firebasemock.MockStorage();
      const mockFire = new firebasemock.MockFirestore();
      mockFire.autoFlush();

      this.auth = mockAut;
      this.storage = mockStor;
      this.firestore = mockFire;
    },
    firestore: mockfirestore,
    auth: mockauth,
    storage: mockstorage,
    functions: jest.fn()
  };
});

Maybe some of you know how to do this in version 2.3.2, do we have a function that makes this in the library ?

Realtime db Ref returns root value rather than the child node

Hi folks, I've got some code that works as expected with the 'real' firebase, but not the mock. Is this a known issue/limitation?

  const mockRealtimeDb = new firebaseMock.MockFirebase();
  mockRealtimeDb.autoFlush(true);
  const mockSdk = new firebaseMock.MockFirebaseSdk(
    () => mockRealtimeDb
  );
  const firebase = mockSdk.initializeApp({});
  await firebase
    .database()
    .ref()
    .update({ "devices/xyz": 123 });
  const savedValue = await firebase
    .database()
    .ref(`devices/xyz`)
    .once('value');
  expect(savedValue.val()).toStrictEqual(123);

however, savedValue.val() returns {"devices": {"xyz": 123}}

updateUser receive wrong parameters

FirebaseAuth.prototype.updateUser = function (newUser) {

Hello guys. I believe this implementation is wrong according firebase-admin updateUser function:
https://github.com/firebase/firebase-admin-node/blob/488f9318350c6b46af2e93b99907b9a02f170029/src/auth/auth.ts#L411

I guess this resolve the problem:

FirebaseAuth.prototype.updateUser = function (uid, newUser) {
  const self = this;
  return new Promise((resolve, reject) => {
    this._defer('updateUser', _.toArray(arguments), () => {
      const i = _.findIndex(self._auth.users, u => u.uid === uid);
      if (i === -1) {
        reject(new Error('Tried to update a nonexistent user'));
      } else {
        Object.keys(newUser).forEach(u => {
          console.log(u);
          self._auth.users[i][u] = newUser[u];
        });
        resolve(self._auth.users[i].clone());
      }
    });
  });
};

And this:

MockFirebaseUser.prototype._refreshIdToken = function () {
  this._tokenValidity.issuedAtTime = new Date();
  this._tokenValidity.expirationTime = defaultExpirationTime(new Date());
  this._idtoken = Math.random().toString();
  return this._auth.updateUser(this.uid, this)
    .then(() => this.getIdTokenResult())
    .catch(() => this.getIdTokenResult());
};

Erratic behavior on interacting with subcollections

Hi,

Thanks for keeping up with firebase-mock!

So I've started to do some testing with firebase-mock with facebook/jest but I'm starting to face a strange problem. When running my tests, sometimes they'll succeed and sometimes they won't if I decide to run some setup inside beforeEach and afterEach:
image

Without changes, running the same tests:
image

I'm not sure if this is some sort of race condition, given that jest parallelizes testing to reduce time. To avoid collisions or unpredictable behavior during my tests (precisely because of that) I generate random IDs before creating new documents for my setup and then use those IDs for testing my REST API. Using --runInBand flag in jest didn't change the outcome though.

I would assume that multiple calls to .set, .delete, .create, and all of those won't affect firebase-mock internals (apart from the data)... but apparently, somehow it does? As you can see in the screenshots, on subsequent tests, for some reason, .set (and further down .delete) does not exist because .doc() is not working as expected for subcollections?

See the code
let EVENT_ID: string;
let GIVEAWAY_ID: string;
let PARTICIPANT_ID: string;
beforeEach(async () => {
  EVENT_ID = cuid();
  GIVEAWAY_ID = cuid();
  PARTICIPANT_ID = getGiveawayParticipantId(GIVEAWAY_ID, 'user1');

  await firestore
    .collection('events')
    .doc(EVENT_ID)
    .set({
      address: 'Address',
      coordinates: new f.GeoPoint(0, 0),
      title: `${EVENT_ID} Event`,
      subtitle: `Subtitle`,
      images: {
        compact: 'https://via.placeholder.com/350x150',
        cover: 'https://via.placeholder.com/350x350'
      },
      startDate: f.Timestamp.fromDate(moment('20200101').toDate()),
    });
  await firestore
    .collection('events')
    .doc(EVENT_ID)
    .collection('giveawayParticipants')
    .doc(PARTICIPANT_ID) // this is where it breaks for some calls
    .set({
      userId: 'user1',
      giveawayId: GIVEAWAY_ID,
      entryDate: f.Timestamp.fromDate(moment('20200101T01').toDate())
    });
});
afterEach(async () => {
  await firestore
    .collection('events')
    .doc(EVENT_ID)
    .delete();
  await firestore
    .collection('events')
    .doc(EVENT_ID)
    .collection('giveawayParticipants')
    .doc(PARTICIPANT_ID) // this is where it breaks for some calls
    .delete();
});

The same strategy works for other tests properly, it's precisely with subcollections where I'm faced with this "sometimes not working" behavior. The issue even occurs within my REST API code (which is mocked with firestore-mock), so it's definitely a thing inside firestore-mock.

See the code
    const batch = this.firebaseService.firestore.batch();
    batch.create(
      this.firebaseService.firestore
        .collection('events')
        .doc(this.eventId)
        .collection('giveawayParticipants')
        .doc(participantId),
      participantData
    );
    // ... some other stuff in the batch

    try {
      await batch.commit();
    } catch (err) {
      // This generates the screenshot's response
      throw new Errors.UnprocessableEntityError(err.message);
    }

This is what I was expecting, but this was literally a struck of luck, after running jest around 3 to 5 times:
image

I'm currently using firebase-mock from master (npm i -s github:dmurvihill/firebase-mock#master).

Update deprecated 'provider' field in docs

Firebase SDK version 4.0.0 replaced the AuthCredential.provider key with a new field named providerId. It looks like the mocking behavior is already updated but some of the documentation was missed. Bring usages of this field up to date.

Co-maintainers needed

Hi everyone,

I'm looking to share the load on this project with up to two co-maintainers. Would be a co-owner on the npm module and expected to review pull requests within 7 days, as well as publish releases if necessary. People who rely on firebase-mock in their professional day-to-day strongly preferred. Apply below.

Behavior on `undefined` fields does not match Firestore

Firestore does not allow for document fields with undefined value. firebase-mock does not seem to simulate this behavior:

firestore.collection('mines').add({
  be: 'happy',
  say: undefined // this throws an error on real Firestore
});

createUser never returns

I have a test that calls a method in my source, that in turn calls Firebase Auth to create a user. But the Promise never resolves, timing out my Mocha test.

Here's the source, simplified:

async function addUser(fb, userInput) {
  await fb.auth().createUser(userInput);
}

And here is my test, simplified:

const firebasemock    = require('firebase-mock');

const mockauth = new firebasemock.MockAuthentication();
const mockdatabase = new firebasemock.MockFirebase();
const mockfirestore = null;
const mockstorage = new firebasemock.MockStorage();
const mockmessaging = null;
const mockfb = new firebasemock.MockFirebaseSdk(
  // use null if your code does not use RTDB
  (path) => {
    return path ? mockdatabase.child(path) : mockdatabase;
  },
  // use null if your code does not use AUTHENTICATION
  () => {
    return mockauth;
  },
  // use null if your code does not use FIRESTORE
  () => {
    return mockfirestore;
  },
  // use null if your code does not use STORAGE
  () => {
    return mockstorage;
  },
  // use null if your code does not use MESSAGING
  () => {
    return mockmessaging;
  }
);

describe('addUser', function () {

    it("createsUser", async () => {
      const testInput = {
        email: "[email protected]"
      }
      await users.addUser(mockfb, testInput);
    });

It basically times out waiting for createUser. Should I use flush here somewhere, or what am I doing wrong?

License

Hello, I found this on npm and was considering using it for a project I am working on. I was wondering what kind of license this is under? I can't seem to find one within the project?

Tests can't run using node v12

Running npm test using node in version 12+ is not possible.

It throws the following error:

> [email protected] test /Users/raman/dev/github/raman-nbg/firebase-mock-backup
> gulp lint && gulp test

fs.js:27
const { Math, Object } = primordials;
                         ^

ReferenceError: primordials is not defined
    at fs.js:27:26
    at req_ (/Users/raman/dev/github/raman-nbg/firebase-mock-backup/node_modules/natives/index.js:143:24)
    at Object.req [as require] (/Users/raman/dev/github/raman-nbg/firebase-mock-backup/node_modules/natives/index.js:55:10)
    at Object.<anonymous> (/Users/raman/dev/github/raman-nbg/firebase-mock-backup/node_modules/graceful-fs/fs.js:1:37)
    at Module._compile (internal/modules/cjs/loader.js:936:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
    at Module.load (internal/modules/cjs/loader.js:790:32)
    at Function.Module._load (internal/modules/cjs/loader.js:703:12)
    at Module.require (internal/modules/cjs/loader.js:830:19)
    at require (internal/modules/cjs/helpers.js:68:18)
npm ERR! Test failed.  See above for more details.

According to Stackoverflow it should be fixable updating to gulp 3 but I didn't try yet.

Cypress Integration Example?

Is there an example of how to integrate this into cypress? I would like to mock the creation of a user with firebase.auth().createUserWithEmailAndPassword() and haven't been able to find an example.

Maybe I should just use Sinon stubs for that but it's not clear what the expected output is from that call?

RTDB References Missing `get`, and `exists` methods

I've been trying to use this repository to test some RTDB code.
However, it seems like references are missing get and exists methods.

I do not see anyone else having this issue, so I'm wondering what can be done.
These methods, are not called directly from my tests, but instead, I pass a reference to a function, and it might, for example, check if it exists.

Mock UserCredential correctly

We are returning the wrong type of object from the signInWith... methods. We are still returning a Promise<User> but Firebase SDK Version 5.0.0 changed these methods to return a Promise<UserCredential> instead.

Typescript definitions

Thanks for the lib. Are there typescript typings available somewhere so that firebase-mock can be used in typescript projects?

mocksdk.database(...).flush is not a function

Following the setup and integration guide with jest, I'm getting the mocksdk.database(...).flush is not a function error. This is my __mock__/firebase-admin.js file:

const jest = require('jest-mock');
var firebasemock    = require('firebase-mock');

var mockauth = new firebasemock.MockAuthentication();
var mockdatabase = new firebasemock.MockFirebase();
var mockfirestore = new firebasemock.MockFirestore();
var mockstorage = new firebasemock.MockStorage();
var mockmessaging = new firebasemock.MockMessaging();
var mocksdk = new firebasemock.MockFirebaseSdk(
  // use null if your code does not use RTDB
  (path) => {
    return path ? mockdatabase.child(path) : mockdatabase;
  },
  // use null if your code does not use AUTHENTICATION
  () => {
    return null;
  },
  // use null if your code does not use FIRESTORE
  () => {
    return mockfirestore;
  },
  // use null if your code does not use STORAGE
  () => {
    return null;
  },
  // use null if your code does not use MESSAGING
  () => {
    return null;
  }
);

mocksdk.initApp = jest.fn();
mocksdk.database().flush();
macksdk.firestore().flush();

module.exports = mocksdk;

and just trying to import it generates the error. I also tried removing the flush declarations from the mocked module and running it on a node shell:

> const admin = require('./firebase-admin')
undefined
> const db = admin.database();
undefined
> db.flush();
TypeError: db.flush is not a function

"Auth token shows user authenticating in the future" if authTime not specified

If authTime is not specified when creating a MockFirebaseUser, the code has a race condition when setting the date at https://github.com/dmurvihill/firebase-mock/blob/master/src/user.js#L170.

Added inline comments on the code from that file

function _tokenValidity(data) {
  const now = new Date(); // Storing "now"
  // If "data.authTime" is not defined, we set it to a new date, which will usually be later than "now"
  const authTime = data.authTime ?
    data.authTime : new Date(); 
 ...
  // If "data.authTime" is not defined, this will most likely trigger 
  } else if (now < authTime) {
    throw new Error(MockFirebaseUser.msg_tokenAuthedInTheFuture);

ship src as esm

Shipping src as esm would be extremely useful. It would obviate the need for a browser bundle, and would be interoperable.

A cjs build could be shipped along side that uses require

If you're interested, I can issue a PR

Negatives of repo being marked as a fork

Just wanted to mention that there are some negatives to having your repo marked as a fork, if you plan to have it up for the long-term:

  1. You can't use the search function (an annoyance I've hit with other forks that "became the main" before)
  2. I believe it also deprioritizes the repo in search results.

So it may be worth deleting and recreating the repo as a "source" repository, before too many people star/watch/fork it.

Request: Mock QuerySnapshot.docChanges() method

Screenshot of issue

image
(Code was copied much straightup from firebase docs)

Description

When running firestore.collection('x').onSnapshot (querySnapshot) => {querySnapshot.docChanges().forEach( ...
which is present here https://googleapis.dev/nodejs/firestore/latest/QuerySnapshot.html#docChanges
I encounter an error saying an error saying the method isn't present.

Was wondering if anyone has been able to mock the docChanges() method in QuerySnapshot? Or if there's a workaround for now

Publish new version on NPM?

The current version published on NPM is quite outdated. It does not have the line that calls the callback of onAuthStateChanged immediately for instance:

callback.call(null, _.cloneDeep(currentUser));

It would be great if the current code in master so we don't have to install the repo directly for the latest code but can make use of regular version of the published package.

Verifying id token

I was following the example here https://github.com/dmurvihill/firebase-mock/blob/master/tutorials/admin/tokens.md and it looks like you are mocking the generation of the id token which returns just a random string:

this._idtoken = Math.random().toString();

once the token is retrieved from the user you call:

function serverLogic(token) {
  firebase.auth().verifyIdToken(token).then(function(user) {
    // do something with the user
    console.log(user.uid);
  });
}

but based on the docs the serverLogic method is not using the mock verifyIdToken method, is that intentional? I ask because if you are not using the mock version of verifyIdToken that Math.random() string will fail to be decoded by the actual firebase auth package.

what is MockFirebase.override();?

in your tutorial you are saying to do MockFirebase.override(); but I can not find anywhere in the doc what is this function.

Your library seems great, but very very hard to understand how it works.

How to mock firebase.firestore namespace?

Problem:
I am using firebase.firestore.Timestamp.now() in my entities constructors in the main app.
I need to be able to use them inside tests as well.
Just importing ts file with entities gives me an error: TypeError: Cannot read property 'Timestamp' of undefined.

I searched everywhere but can't find a solution to this problem. Can someone help? (Ideally with a code example)

Feature request: Support '>' in firestore query

Hello

I need to check data by query like where('x','>',1) right now I get Using unsupported where() operator for firebase-mock, returning entire dataset message, I was wondering if developing the other filters than == and array-contains is in the plan?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.