简体   繁体   中英

How can I test my react js + firestore project if I didn't use cloud functions?

I'm learning full stack developement and I've just I finished my first react js + firestore project. I want write some unit tests, but the only samples I found on the internet are testing firestore rules or testing cloud functions. I want to test for example my queries whether they return the expected value.

export async function doesUsernameExist(username) {
  const result = await firebase
    .firestore()
    .collection('users')
    .where('username', '==', username) 
    .get();

  return result.docs.map((user) => user.data().length > 0);
}

I want to test this query with a fake data, but how can I make a fake data? To be more exact, I need a data structure I can query on. Thank you in advance!

I solved my problem. I used firebase emulator. In my case the solution is:

instead of

const firebase = Firebase.initializeApp(config);

use this config

const firebase = require('@firebase/testing')

const db = firebase.initializeTestApp({ projectId: MY_PRIJECT_ID }).firestore()



async function doesUsernameExist(username) {
      const result = await db
        .collection('users')
        .where('username', '==', username)
        .get();
      return result.docs.map((user) => user.data().length > 0);
    }
    
    describe('Testing username', () => {
      it('Username does not exsitst in the database', async () => {
        const username = "peter"
        const res = await doesUsernameExist(username)
    
        expect(res.length).toEqual(0)
      })
    
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM