my route handler is, I wanna write using mocha and sinon and possibly supertest but if your code works in jest please send that too
router.post('/sign-up', async (req, res) => {
try {
const { username, password } = req.body
await registerUser(username, password)
res.status(201).send('user createdn')
} catch (error) {
if (error.message === 'username and password are required') {
return res.status(400).send(error.message + 'n')
}
if (error.message === 'username already exists') {
return res.status(409).send(error.message + 'n')
}
console.error(error)
res.status(500).send('internal server errorn')
}
})
I wanna stub await registerUser call to resolve it for testing, but It keeps calling the actual code hence causes connecting to database and hangs. the registerUser code is also
const bcrypt = require('bcrypt');
const saltRounds = 10;
// Import the repository functions
const userRepository = require('./userRepository');
async function registerUser(username, password) {
if (!username || !password) {
throw new Error('Username and password are required');
}
// Check if the username already exists in the database
const existingUser = await userRepository.findOne({ username });
if (existingUser) {
throw new Error('Username already exists');
}
// Hash the password for storing in the database
const hashedPassword = await bcrypt.hash(password, saltRounds);
// Create and save the user to the database
await userRepository.save({
username,
password: hashedPassword,
});
}
module.exports = { registerUser };
I expect the registerUser to be resolved with stubbing Ideally using sinon.