diff --git a/src/user.js b/src/user.js index 50b7eadf..23f6ff30 100644 --- a/src/user.js +++ b/src/user.js @@ -19,7 +19,7 @@ function MockFirebaseUser(ref, data) { this.emailVerified = !!data.emailVerified; this.isAnonymous = !!data.isAnonymous; this.metadata = data.metadata; - this.providerData = data.providerData; + this.providerData = data.providerData || []; this.providerId = data.providerId; this.refreshToken = data.refreshToken; } @@ -123,6 +123,26 @@ MockFirebaseUser.prototype.getIdToken = function (forceRefresh) { }); }; +MockFirebaseUser.prototype.toJSON = function() { + const json = { + uid: this.uid, + email: this.email, + emailVerified: this.emailVerified, + displayName: this.displayName, + photoURL: this.photoURL, + phoneNumber: this.phoneNumber, + }; + if (this.metadata) { + json.createdAt = this.metadata.createdAt; + json.lastLoginAt = this.metadata.lastLoginAt; + } + json.providerData = []; + for (const entry of this.providerData) { + json.providerData.push(entry.toJSON()); + } + return json; +}; + MockFirebaseUser.prototype.getIdTokenResult = function (forceRefresh) { if (forceRefresh) { this._refreshIdToken(); diff --git a/test/unit/user.js b/test/unit/user.js index 5ea3082f..d9e70514 100644 --- a/test/unit/user.js +++ b/test/unit/user.js @@ -463,6 +463,48 @@ describe('User', function() { return expect(user._refreshIdToken()).not.to.be.rejected; }); }); + + describe('#toJSON', () => { + describe('most fields', () => { + it('should be the same', () => { + const user = new User(auth, {}); + const json = user.toJSON(); + [ + 'uid', + 'email', + 'emailVerified', + 'displayName', + 'photoURL', + 'phoneNumber', + 'providerData', + ].forEach(k => expect(json[k]).to.deep.equal(user[k])); + }); + }); + + describe('.metadata', () => { + it('keys should be missing if omitted', () => { + const user = new User(auth, {}); + expect(user.toJSON()).not.to.haveOwnProperty('lastLoginAt'); + expect(user.toJSON()).not.to.haveOwnProperty('createdAt'); + }); + + it('should populate to lastLogin if present', () => { + const metadata = { + lastLoginAt: new Date(11).getTime().toString(10), + }; + const user = new User(auth, { metadata: metadata, }); + expect(user.toJSON().lastLoginAt).to.equal(metadata.lastLoginAt); + }); + + it('should populate to createdAt if present', () => { + const metadata = { + createdAt: new Date(12).getTime().toString(10), + }; + const user = new User(auth, { metadata: metadata, }); + expect(user.toJSON().createdAt).to.equal(metadata.createdAt); + }); + }); + }); }); function randomTimestamp() {