73
loading...
This website collects cookies to deliver better user experience
// api/listUsers.js
const firebase = require('../services/firebase')
const PAGE_SIZE = 1000
module.exports = async function (data, context) {
let allUsers = []
let { users, pageToken } = await firebase.auth().listUsers(PAGE_SIZE)
do {
allUsers = allUsers.concat(users.map(user => user.uid))
if (pageToken) {
({ users, pageToken } = await firebase.auth().listUsers(PAGE_SIZE, pageToken))
}
} while (pageToken)
return { users: allUsers }
}
pageToken
to check if there are more pages and concatenate that in one single response.yarn add --dev jest # Or `npm install --save-dev jest`
yarn add --dev @types/jest # or `npm install --save-dev @types/jest`
// test/api/listUsers.test.js
const admin = require('firebase-admin')
process.env.FIREBASE_AUTH_EMULATOR_HOST = 'localhost:9099'
const test = require('firebase-functions-test')()
// Mock config values here
const functions = require('../../index.js') // import functions *after* initializing Firebase
describe('listUsers', () => {
let wrapped
beforeAll(() => {
wrapped = test.wrap(functions.listUsers)
})
afterAll(() => {
test.cleanup()
})
// tests will go here
})
firebase-functions-test
without parameters. Because of this, all calls to Firebase will be using the project default’s — most likely your production. We obviously don’t want this. That’s why we initialized it after the following line.process.env.FIREBASE_AUTH_EMULATOR_HOST = 'localhost:9099'
it('returns an empty array when there are no users', async () => {
const { users } = await wrapped()
expect(users).toEqual([])
})
Error while making request: connect ECONNREFUSED 127.0.0.1:9099. Error code: ECONNREFUSED
If you don’t get this error, make sure you’ve updated the environment variable and initialized firebase-functions-test
without configuration. Your app might be trying to connect to production.
yarn add --dev firebase-tools # or `npm install -save-dev firebase-tools`
emulators:exec
command to launch the Auth service emulator and run our tests. For convenience, I included it in my package.json
.// package.json
"scripts": {
"test:run": "jest ./test/",
// If you're using Yarn
"test": "firebase emulators:exec --only auth 'yarn test:run'",
// If you're using NPM
"test": "firebase emulators:exec --only auth 'npm run test:run'"
}
--only
parameter to include the other services you need.73