Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Query class #37

Merged
merged 8 commits into from
Sep 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,19 +186,26 @@ Your application doesn't double-check firestore's response -- it trusts that it'
| `mockCollection` | Assert the correct collection is being queried | [collection](https://googleapis.dev/nodejs/firestore/latest/Firestore.html#collection) |
| `mockCollectionGroup` | Assert the correct collectionGroup is being queried | [collectionGroup](https://googleapis.dev/nodejs/firestore/latest/Firestore.html#collectionGroup) |
| `mockDoc` | Assert the correct record is being fetched by id. Tells the mock you are fetching a single record | [doc](https://googleapis.dev/nodejs/firestore/latest/Firestore.html#doc) |
| `mockWhere` | Assert the correct query is written. Tells the mock you are fetching multiple records | [where](https://googleapis.dev/nodejs/firestore/latest/Query.html#where) |
| `mockBatch` | Assert batch was called | [batch](https://googleapis.dev/nodejs/firestore/latest/Firestore.html#batch) |
| `mockBatchDelete` | Assert correct refs are passed | [batch delete](https://googleapis.dev/nodejs/firestore/latest/WriteBatch.html#delete) |
| `mockBatchCommit` | Assert commit is called. Returns a promise | [batch commit](https://googleapis.dev/nodejs/firestore/latest/WriteBatch.html#commit) |
| `mockGet` | Assert get is called. Returns a promise resolving either to a single doc or querySnapshot | [get](https://googleapis.dev/nodejs/firestore/latest/Query.html#get) |
| `mockGetAll` | Assert correct refs are passed. Returns a promise resolving to array of docs. | [getAll](https://googleapis.dev/nodejs/firestore/latest/Firestore.html#getAll) |
| `mockUpdate` | Assert correct params are passed to update. Returns a promise | [update](https://googleapis.dev/nodejs/firestore/latest/DocumentReference.html#update) |
| `mockAdd` | Assert correct params are passed to add. Returns a promise resolving to the doc with new id | [add](https://googleapis.dev/nodejs/firestore/latest/CollectionReference.html#add) |
| `mockSet` | Assert correct params are passed to set. Returns a promise | [set](https://googleapis.dev/nodejs/firestore/latest/DocumentReference.html#set) |
| `mockDelete` | Assert delete is called on ref. Returns a promise | [delete](https://googleapis.dev/nodejs/firestore/latest/DocumentReference.html#delete) |
| `mockOrderBy` | Assert correct field is passed to orderBy | [orderBy](https://googleapis.dev/nodejs/firestore/latest/Query.html#orderBy) |
| `mockLimit` | Assert limit is set properly | [limit](https://googleapis.dev/nodejs/firestore/latest/Query.html#limit) |
| `mockOffset` | Assert offset is set properly | [offset](https://googleapis.dev/nodejs/firestore/latest/Query.html#offset) |

#### [Firestore.Query](https://googleapis.dev/nodejs/firestore/latest/Query.html)

| Method | Use | Method in Firestore |
| ---------------- | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `mockGet` | Assert get is called. Returns a promise resolving either to a single doc or querySnapshot | [get](https://googleapis.dev/nodejs/firestore/latest/Query.html#get) |
| `mockWhere` | Assert the correct query is written. Tells the mock you are fetching multiple records | [where](https://googleapis.dev/nodejs/firestore/latest/Query.html#where) |
| `mockLimit` | Assert limit is set properly | [limit](https://googleapis.dev/nodejs/firestore/latest/Query.html#limit) |
| `mockOrderBy` | Assert correct field is passed to orderBy | [orderBy](https://googleapis.dev/nodejs/firestore/latest/Query.html#orderBy) |
| `mockOffset` | Assert offset is set properly | [offset](https://googleapis.dev/nodejs/firestore/latest/Query.html#offset) |
| `mockStartAfter` | Assert startAfter is called | [startAfter](https://googleapis.dev/nodejs/firestore/latest/Query.html#startAfter) |
| `mockStartAt` | Assert startAt is called | [startAt](https://googleapis.dev/nodejs/firestore/latest/Query.html#startAt) |

#### [Firestore.FieldValue](https://googleapis.dev/nodejs/firestore/latest/FieldValue.html)

Expand Down
89 changes: 55 additions & 34 deletions __tests__/query.test.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,34 @@
const { mockCollection, mockGet, mockWhere, mockOffset } = require('../mocks/firestore');

const {
mockCollection,
mockGet,
mockWhere,
mockOffset,
FakeFirestore,
} = require('../mocks/firestore');
const { mockFirebase } = require('firestore-jest-mock');

describe('test', () => {
test('It can query firestore', async () => {
mockFirebase({
database: {
animals: [
{ name: 'monkey', type: 'mammal' },
{ name: 'elephant', type: 'mammal' },
],
},
currentUser: { uid: 'homer-user' },
});
const firebase = require('firebase');
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###',
});
mockFirebase({
database: {
animals: [
{ id: 'monkey', name: 'monkey', type: 'mammal' },
{ id: 'elephant', name: 'elephant', type: 'mammal' },
{ id: 'chicken', name: 'chicken', type: 'bird' },
{ id: 'ant', name: 'ant', type: 'insect' },
],
},
currentUser: { uid: 'homer-user' },
});
const firebase = require('firebase');
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###',
});

const db = firebase.firestore();
const db = firebase.firestore();

test('It can query firestore', async () => {
const animals = await db
.collection('animals')
.where('type', '==', 'mammal')
Expand All @@ -33,24 +40,38 @@ describe('test', () => {
expect(mockGet).toHaveBeenCalled();
});

test('It can offset query', async () => {
mockFirebase({
database: {
animals: [
{ name: 'monkey', type: 'mammal' },
{ name: 'elephant', type: 'mammal' },
{ name: 'lion', type: 'mammal' },
],
test('it returns a Query from query methods', () => {
const ref = db.collection('animals');
expect(ref.where('type', '==', 'mammal')).toBeInstanceOf(FakeFirestore.Query);
expect(ref.limit(1)).toBeInstanceOf(FakeFirestore.Query);
expect(ref.orderBy('type')).toBeInstanceOf(FakeFirestore.Query);
expect(ref.startAfter(null)).toBeInstanceOf(FakeFirestore.Query);
expect(ref.startAt(null)).toBeInstanceOf(FakeFirestore.Query);
});

test('it permits mocking the results of a where clause', async () => {
expect.assertions(2);
const ref = db.collection('animals');

let result = await ref.where('type', '==', 'mammal').get();
expect(result.docs.length).toBe(4);

// There's got to be a better way to mock like this, but at least it works.
mockWhere.mockReturnValueOnce({
get() {
return Promise.resolve({
docs: [
{ id: 'monkey', name: 'monkey', type: 'mammal' },
{ id: 'elephant', name: 'elephant', type: 'mammal' },
],
});
},
});
const firebase = require('firebase');
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###',
});
result = await ref.where('type', '==', 'mammal').get();
expect(result.docs.length).toBe(2);
});

const db = firebase.firestore();
test('It can offset query', async () => {
const firstTwoMammals = await db
.collection('animals')
.where('type', '==', 'mammal')
Expand Down
3 changes: 1 addition & 2 deletions mocks/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ const mockGetUser = jest.fn();
const mockSetCustomUserClaims = jest.fn();

class FakeAuth {
constructor(currentUser) {
currentUser = currentUser || {};
constructor(currentUser = {}) {
currentUser.sendEmailVerification = mockSendVerificationEmail;
this.currentUserRecord = currentUser;
}
Expand Down
81 changes: 31 additions & 50 deletions mocks/firestore.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
const mockCollection = jest.fn();
const mockCollectionGroup = jest.fn();
const mockDoc = jest.fn();
const mockWhere = jest.fn();
const mockBatch = jest.fn();
const mockGet = jest.fn();
const mockGetAll = jest.fn();
const mockUpdate = jest.fn();
const mockAdd = jest.fn();
const mockSet = jest.fn();
const mockDelete = jest.fn();
const mockOrderBy = jest.fn();
const mockLimit = jest.fn();
const mockOffset = jest.fn();

const mockArrayRemoveFieldValue = jest.fn();
const mockArrayUnionFieldValue = jest.fn();
Expand All @@ -24,48 +19,29 @@ const mockBatchCommit = jest.fn();
const mockBatchUpdate = jest.fn();
const mockBatchSet = jest.fn();

function buildDocFromHash(hash = {}) {
return {
exists: !!hash || false,
id: hash.id || 'abc123',
data() {
const copy = { ...hash };
delete copy.id;
return copy;
},
};
}
const { Query, mocks } = require('./query');

const buildDocFromHash = require('./helpers/buildDocFromHash');
const buildQuerySnapShot = require('./helpers/buildQuerySnapShot');

function idHasCollectionName(id) {
return id.match('/');
}

function buildQuerySnapShot(requestedRecords) {
const multipleRecords = requestedRecords.filter(rec => !!rec);
const docs = multipleRecords.map(buildDocFromHash);

return {
empty: multipleRecords.length < 1,
docs,
forEach(callback) {
return docs.forEach(callback);
},
};
}

class FakeFirestore {
constructor(stubbedDatabase = {}) {
this.isFetchingSingle = false;
this.database = stubbedDatabase;
this.query = new Query('', this);
}

set collectionName(collectionName) {
this._collectionName = collectionName;
this.query.collectionName = collectionName;
this.recordToFetch = null;
}

get collectionName() {
return this._collectionName;
return this.query.collectionName;
}

collection(collectionName) {
Expand All @@ -82,15 +58,8 @@ class FakeFirestore {
return this;
}

where() {
this.isFetchingSingle = false;
mockWhere(...arguments);
return this;
}

get() {
mockGet(...arguments);
AverageHelper marked this conversation as resolved.
Show resolved Hide resolved

mocks.mockGet(...arguments);
if (this.recordToFetch) {
return Promise.resolve(buildDocFromHash(this.recordToFetch));
}
Expand Down Expand Up @@ -156,6 +125,11 @@ class FakeFirestore {
return this;
}

where() {
this.isFetchingSingle = false;
return this.query.where(...arguments);
}

update(object) {
mockUpdate(...arguments);
return Promise.resolve(buildDocFromHash(object));
Expand All @@ -177,21 +151,28 @@ class FakeFirestore {
}

orderBy() {
mockOrderBy(...arguments);
return this;
return this.query.orderBy(...arguments);
AverageHelper marked this conversation as resolved.
Show resolved Hide resolved
}

limit() {
mockLimit(...arguments);
return this;
return this.query.limit(...arguments);
}

offset() {
mockOffset(...arguments);
return this;
return this.query.offset(...arguments);
}

startAfter() {
return this.query.startAfter(...arguments);
}

startAt() {
return this.query.startAt(...arguments);
}
}

FakeFirestore.Query = Query;

FakeFirestore.FieldValue = class {
constructor(type, value) {
this.type = type;
Expand Down Expand Up @@ -296,14 +277,14 @@ module.exports = {
mockCollectionGroup,
mockDelete,
mockDoc,
mockGet,
mockGet: mocks.mockGet,
mockGetAll,
mockOrderBy,
mockLimit,
mockOffset,
mockOrderBy: mocks.mockOrderBy,
mockLimit: mocks.mockLimit,
mockOffset: mocks.mockOffset,
mockSet,
mockUpdate,
mockWhere,
mockWhere: mocks.mockWhere,
mockArrayRemoveFieldValue,
mockArrayUnionFieldValue,
mockDeleteFieldValue,
Expand Down
14 changes: 14 additions & 0 deletions mocks/helpers/buildDocFromHash.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module.exports = function buildDocFromHash(hash = {}) {
return {
exists: !!hash || false,
id: hash.id || 'abc123',
ref: hash._ref,
data() {
const copy = { ...hash };
delete copy.id;
delete copy._collections;
delete copy._ref;
return copy;
},
};
};
15 changes: 15 additions & 0 deletions mocks/helpers/buildQuerySnapShot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const buildDocFromHash = require('./buildDocFromHash');

module.exports = function buildQuerySnapShot(requestedRecords) {
const multipleRecords = requestedRecords.filter(rec => !!rec);
const docs = multipleRecords.map(buildDocFromHash);

return {
empty: multipleRecords.length < 1,
size: multipleRecords.length,
docs,
forEach(callback) {
return docs.forEach(callback);
},
};
};
Loading