cloud_firestore_mocks 0.4.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 88

Mocks to write unit tests for Cloud Firestore. Instantiate a MockFirestoreInstance, then pass it around your project as if it were a FirestoreInstance. This mock will act like Firestore except it will only keep the state in memory. To help debug, you can use MockFirestoreInstance.dump() to see what's in the mock database. This is useful to mock the state of your database, then check that your UI behaves the way you expect.

Usage #

A simple usage example #

import 'package:cloud_firestore_mocks/cloud_firestore_mocks.dart';

void main() {
  final instance = MockFirestoreInstance();
  await instance.collection('users').add({
    'username': 'Bob',
  });
  final snapshot = await instance.collection('users').getDocuments();
  print(snapshot.documents.length); // 1
  print(snapshot.documents.first['username']); // 'Bob'
  print(instance.dump());
}

// Prints out:
// {
//   "users": {
//     "z": {
//       "name": "Bob"
//     }
//   }
// }

See more examples at cloud_firestore_mocks/test/cloud_firestore_mocks_test.dart.

Usage in a UI test: #

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cloud_firestore_mocks/cloud_firestore_mocks.dart';
import 'package:firestore_example/main.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

const MessagesCollection = 'messages';

void main() {
  testWidgets('shows messages', (WidgetTester tester) async {
    // Populate the mock database.
    final firestore = MockFirestoreInstance();
    await firestore.collection(MessagesCollection).add({
      'message': 'Hello world!',
      'created_at': FieldValue.serverTimestamp(),
    });

    // Render the widget.
    await tester.pumpWidget(MaterialApp(
        title: 'Firestore Example', home: MyHomePage(firestore: firestore)));
    // Let the snapshots stream fire a snapshot.
    await tester.idle();
    // Re-render.
    await tester.pump();
    // // Verify the output.
    expect(find.text('Hello world!'), findsOneWidget);
    expect(find.text('Message 1 of 1'), findsOneWidget);
  });
}

See more examples at cloud_firestore_mocks/example/test/widget_test.dart.

Features #

  • Dump the state of the mock firebase with MockFirestoreInstance.dump().
  • Create documents and collections.
  • Create documents with collection.add or document.setData.
  • Batch writes.
  • Query documents with collection.snapshots or query.getDocuments.
  • Queries:
    • Filter results with query.where. The library supports equals, isGreaterThan, isGreaterThanOrEqualTo, isLessThan, and isLessThanOrEqualTo.
    • Sort results with query.orderBy.
    • Limit results with query.limit.
  • ValueField:
    • set timestamps with FieldValue.serverTimestamp().
    • delete values with ValueField.delete().

Features and bugs #

Please file feature requests and bugs at the issue tracker.

0.4.1 #

  • CollectionReference.getDocuments returns only documents that have been saved by CollectionReference.add or DocumentReference.setData or DocumentReference.updateData.
  • make CollectionReference.add generate a random documentId.
  • support batch operations updateData and delete.
  • implemented DocumentReference.path.
  • implemented DocumentSnapshot.reference.

Thank you suztomo for contributing these improvements!

0.4.0+1 #

  • fixed some lint error.

0.4.0 #

  • support CollectionReference.document(). Thanks suztomo!
  • support nested documents. Thanks suztomo!
  • support FieldValue.serverTimestamp(). Thanks suztomo!
  • breaking change: remove requirement to call setupFieldValueFactory(). They are now initialized automatically when MockFirestoreInstance is instantiated.

0.3.1 #

  • support FieldValue.delete() again.

0.3.0 #

  • fixed breakage due to FieldValue.type and FieldValue.value being removed from the public API at cloud_firestore 0.10.0.
  • implemented chainable Query.where. Thank you qwales1!
  • dropped support for FieldValue.delete().

0.2.7 #

  • implemented DocumentSnapshot.exists. Thank you qwales1!

0.2.6 #

0.2.5 #

  • upgraded cloud_firestore to ^0.13.0+1.

0.2.4 #

  • cleaned up the public documentation to expose only MockFirestoreInstance.

0.2.3 #

  • fixed code health related issues.

0.2.2 #

  • added support for isGreaterThanOrEqualTo, isLessThan, isLessThanOrEqualTo in CollectionReference.where.
  • implemented mock DocumentReference.delete.

0.2.1 #

  • Fixed snapshots not firing several times.
  • Implemented example unit tests based on Firestore's own example project.

0.2.0 #

  • Initial version.

example/lib/main.dart

// Copyright 2017, the Chromium project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final FirebaseApp app = await FirebaseApp.configure(
    name: 'test',
    options: const FirebaseOptions(
      googleAppID: '1:79601577497:ios:5f2bcc6ba8cecddd',
      gcmSenderID: '79601577497',
      apiKey: 'AIzaSyArgmRGfB5kiQT6CunAOmKRVKEsxKmy6YI-G72PVU',
      projectID: 'flutter-firestore',
    ),
  );
  final Firestore firestore = Firestore(app: app);
  await firestore.settings();

  runApp(MaterialApp(
      title: 'Firestore Example', home: MyHomePage(firestore: firestore)));
}

class MessageList extends StatelessWidget {
  MessageList({this.firestore});

  final Firestore firestore;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: firestore.collection('messages').snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (!snapshot.hasData) return const Text('Loading...');
        final int messageCount = snapshot.data.documents.length;
        return ListView.builder(
          itemCount: messageCount,
          itemBuilder: (_, int index) {
            final DocumentSnapshot document = snapshot.data.documents[index];
            final dynamic message = document['message'];
            return ListTile(
              title: Text(
                message != null ? message.toString() : '<No message retrieved>',
              ),
              subtitle: Text('Message ${index + 1} of $messageCount'),
            );
          },
        );
      },
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({this.firestore});

  final Firestore firestore;

  CollectionReference get messages => firestore.collection('messages');

  Future<void> _addMessage() async {
    await messages.add(<String, dynamic>{
      'message': 'Hello world!',
      'created_at': FieldValue.serverTimestamp(),
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Firestore Example'),
      ),
      body: MessageList(firestore: firestore),
      floatingActionButton: FloatingActionButton(
        onPressed: _addMessage,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  cloud_firestore_mocks: ^0.4.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:cloud_firestore_mocks/cloud_firestore_mocks.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
79
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
95
Overall:
Weighted score of the above. [more]
88
Learn more about scoring.

We analyzed this package on Mar 31, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8

Health suggestions

Format lib/src/cloud_firestore_mocks_base.dart.

Run flutter format to format lib/src/cloud_firestore_mocks_base.dart.

Format lib/src/mock_collection_reference.dart.

Run flutter format to format lib/src/mock_collection_reference.dart.

Format lib/src/mock_document_reference.dart.

Run flutter format to format lib/src/mock_document_reference.dart.

Format lib/src/mock_query.dart.

Run flutter format to format lib/src/mock_query.dart.

Maintenance suggestions

Homepage URL is insecure. (-5 points)

Update the homepage field and use a secure (https) URL.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.0 <3.0.0
cloud_firestore ^0.13.1+1 0.13.4+2
cloud_firestore_platform_interface ^1.0.0 1.1.0
flutter 0.0.0
mockito ^4.1.0 4.1.1
plugin_platform_interface ^1.0.1 1.0.2
Transitive dependencies
async 2.4.1
boolean_selector 2.0.0
charcode 1.1.3
cloud_firestore_web 0.1.1+2
collection 1.14.11 1.14.12
firebase 7.2.1
firebase_core 0.4.4+3
firebase_core_platform_interface 1.0.4
firebase_core_web 0.1.1+2
flutter_web_plugins 0.0.0
http 0.12.0+4
http_parser 3.1.4
js 0.6.1+1
matcher 0.12.6
meta 1.1.8
path 1.6.4
quiver 2.1.3
sky_engine 0.0.99
source_span 1.7.0
stack_trace 1.9.3
stream_channel 2.0.0
string_scanner 1.0.5
term_glyph 1.1.0
test_api 0.2.15
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test
pedantic ^1.0.0 1.9.0
test ^1.0.0