title: How to mock data for testing Firestore with emulator
body: <p>I am testing my Firestore security rules and have the following setup:</p>
  <pre><code>// firestore.spec.js
  /**
   * Creates a new client FirebaseApp with authentication and returns the Firestore instance.
   * Also optionally seeds the project with mock data
   */
  setupFirestoreDb = async (auth, data) =&gt; {
    // initialize test app
    const PROJECT_ID = &quot;my-test-project-xyz&quot;;
    const app = firebase.initializeTestApp({ projectId: PROJECT_ID, auth });
    const db = app.firestore();
  
    // Write mock documents
    if (data) {
      for (const key in data) {
        const ref = db.doc(key);
        ref.set(data[key]);
      }
    }
  
    return db;
  };
  
  beforeEach(async () =&gt; {
    // Clear the database between tests
    await firebase.clearFirestoreData({ projectId: PROJECT_ID });
  });
  
  before(async () =&gt; {
    // Load the rules file before the tests begin
    const rules = fs.readFileSync(&quot;firestore.rules&quot;, &quot;utf8&quot;);
    await firebase.loadFirestoreRules({ projectId: PROJECT_ID, rules });
  });
  
  after(async () =&gt; {
    // Delete all the FirebaseApp instances created during testing
    // Note: this does not affect or clear any data
    await Promise.all(firebase.apps().map((app) =&gt; app.delete()));
  });
  
  const mockData = {
    'users/alice': {
      foo: 'bar',
      nestedData: {
        baz: 'fae'
      }
    },
    'users/bob': {
      foo: 'bar',
      nestedData: {
        baz: 'fae'
      }
    },
    // ... more data
  }
  
  // run the test suite
  describe(&quot;Test Security Rules&quot;, () =&gt; {
  
    it(&quot;should let any signed-in user to read any public profile&quot;, async () =&gt; {
      let db = await setupFirestoreDb({uid: &quot;bob&quot;}, mockData);
      aliceRef = db.collection(&quot;users&quot;).doc(&quot;alice&quot;);
      await firebase.assertSucceeds(aliceRef.get()); // fails
    });
  
      // more test cases
      ...
  
  });
  </code></pre>
  <p>And my security rules file:</p>
  <pre><code>// firestore.rules
  rules_version = '2';
  
  service cloud.firestore {
    match /databases/{database}/documents {
      // define common functions used across collections/documents
  
      function userExists() {
        return exists(/databases/$(database)/documents/users/$(request.auth.uid));
      }
  
      // Fetch a user from Firestore by UID
      function getUserData(uid) {
        return get(/databases/$(database)/documents/users/$(uid)).data
      }
  
      function isValidUser() {
        let userData = request.resource.data;
        return userData.name != null &amp;&amp; userData.phoneNumber != null;
      }
  
      // ... more functions
  
      // lock the entire database by default
      match /{document=**} {
        allow read, write: if false;
      }
  
      // rules for users collection
      match /users/{userId} {
        allow read: if isSignedIn() &amp;&amp; getUserData(userId) != null; // &amp;&amp; userExists(userId); // make sure user being read exists
        allow write: if isSignedIn() &amp;&amp; isUser(userId) &amp;&amp; isValidUser(); // only an authenticated user can create own account
  
        // ... other rules for nested data (subcollections)
      }
  
      // ... more rules 
    }
  }
  </code></pre>
  <h3>The test fails with:</h3>
  <p><code>FirebaseError: false for 'get' @ L*, Null value error. for 'get' @ L*</code>, which occurs because I believe the function <code>getUserData()</code> returns null (same for <code>userExists()</code>).</p>
  <h3>Instead, I expected <code>getUserData()</code> to return true because the document for user 'alice' is created based on the mock data.</h3>
  <p>Is it a problem with the Firestore emulator or is there something wrong with how I set up my mock data &amp; test fixture? I used the Firebase simulator on the console to test the same rules against a real database and the rules work (<code>getUserData()</code> and <code>userExists()</code> work as expected)</p>
  <p>The code is largely based on this <a href="https://fireship.io/lessons/testing-firestore-security-rules-with-the-emulator/" rel="nofollow noreferrer">fireship tutorial</a> and the official firebase <a href="https://github.com/firebase/quickstart-testing/blob/master/unit-test-security-rules/README.md" rel="nofollow noreferrer">unit testing tutorial</a></p>