1 | initial version |
It is possible to generate a user with a password in Firebase functions by utilizing Auth and the Firebase emulator. Here's an example code snippet for generating a user with email and password using the Firebase emulator:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.createUser = functions.https.onRequest((req, res) => {
// Create a user with email and password
admin.auth().createUser({
email: 'example@example.com',
password: 'password123'
})
.then((userRecord) => {
console.log('Created user with uid:', userRecord.uid);
res.status(200).send('User created successfully');
})
.catch((error) => {
console.error('Error creating user:', error);
res.status(500).send('Error creating user');
});
});
To test this function locally in the Firebase emulator, you can use the firebase-functions-test library. Here's an example test case:
const test = require('firebase-functions-test')();
const admin = require('firebase-admin');
const myFunctions = require('../index');
describe('createUser', () => {
beforeEach(() => {
// Set up admin SDK mock
admin.initializeApp({
databaseURL: 'https://my-project.firebaseio.com',
credential: admin.credential.applicationDefault()
});
});
afterEach(() => {
test.cleanup();
});
it('should create a user with email and password', () => {
// Mock the request and response objects
const req = { body: {} };
const res = { send: jest.fn() };
// Call the function
myFunctions.createUser(req, res);
// Check the response
expect(res.send).toHaveBeenCalledWith('User created successfully');
});
});
Note that in the test case, we're mocking the Firebase Admin SDK using the firebase-functions-test
library. This allows us to test the function locally without actually calling the Firebase API.