dmurvihill / firebase-mock Goto Github PK
View Code? Open in Web Editor NEWThis project forked from soumak77/firebase-mock
Firebase mock library for writing unit tests
This project forked from soumak77/firebase-mock
Firebase mock library for writing unit tests
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
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 ?
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}}
Firestore now has this enabled by default as of 5.8.0. It's a breaking change in a minor release so we should get consistent with their behavior ASAP.
firebase-mock/src/firebase-auth.js
Line 102 in 4a6a54d
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());
};
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
:
Without changes, running the same tests:
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?
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
.
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:
I'm currently using firebase-mock
from master
(npm i -s github:dmurvihill/firebase-mock#master
).
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.
version 6.5.0 added waitForPendingWrites
.
Firebase SDK 6.1.0 added the ability to list items in a bucket.
Firebase SDK version 5.3.0 added some new array methods to Firestore that we should be able to mock.
Firestore now has this enabled by default as of 5.8.0. It's a breaking change in a minor release so we should get consistent with their behavior ASAP.
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.
Firebase SDK version 4.12.0 added support for magic link sign in. Let's mock it.
Firebase SDK version 4.4.0 added support for sharding. This would be really killer if we could mock it well.
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
});
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?
Firebase SDK version 5.3.0 added some new array methods to Firestore that we should be able to mock.
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?
Version 4.0.0 changed the behavior of onAuthStateChanged
and added a new event handler called onIdTokenChanged
. We need to correctly mock it.
Also, let's mock User.getIdTokenResult
from 4.13.0.
Firebase SDK 5.9.0 added this neat new method that we should mock.
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.
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?
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
.
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.
Firebase SDK Version 4.0.0 and later added a family of linkWith...
methods to the User object. We should help users to mock their behavior.
https://firebase.google.com/docs/reference/js/firebase.User.html#linkwithcredential
Note, however, that 5.0.0 deprecated some of these methods in favor of new ones.
Thanks for the lib. Are there typescript typings available somewhere so that firebase-mock can be used in typescript projects?
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
I suppose that we should be able to prepare our bucket for testing. But now, unfortunately, there is no any possibility to do that.
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);
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
Firebase SDK Version 4.0.0 and later added a family of reauthenticateWith...
methods to the User object. We should help users to mock their behavior.
https://firebase.google.com/docs/reference/js/firebase.User.html#reauthenticatewithcredential
This was added in 5.10.0 and should be easy to implement.
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:
So it may be worth deleting and recreating the repo as a "source" repository, before too many people star/watch/fork it.
Firebase SDK version 4.9.0 added support for the disableNetwork
and enableNetwork
commands in Firestore but we do not yet mock them.
Version 4.0.0 added support for phone number authentication. Let's try and mock it.
Docs on it here: https://firebase.google.com/docs/firestore/query-data/queries#collection-group-query.
I added a very rough and ugly version in my fork: siteline@cfd816c. This isn't perfect by any means and only handled/solved my use-case.
(Code was copied much straightup from firebase docs)
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
Firebase SDK version 4.2.0 added support for configuring authentication state persistence. Let's mock it!
https://firebase.google.com/docs/auth/web/auth-state-persistence
Hi would anyone like to take a stab at mocking analytics for me.
The current version published on NPM is quite outdated. It does not have the line that calls the callback of onAuthStateChanged
immediately for instance:
firebase-mock/src/firebase-auth.js
Line 33 in 4a6a54d
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.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.
The original project is orphaned (see here) so we need to get publish permissions so we can resume releasing code.
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.
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)
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?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.