I have decided to implement a TDD approach for a user API that I am working on. Specifically, I am looking to add unit tests for two functions: userRegister and userLogin.
Here is the code snippet from my app.js:
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const passport = require('passport')
const users = require('../routes/users')
const app = express()
const port = 5000
app.get('/', (req, res) => {
res.send({ msg: 'Test' })
})
//BodyParser Middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//Passport middleware
app.use(passport.initialize())
//Initialize Routes
app.use('/api/users', users)
//Export app
module.exports = app
Next, here is the content of my userController.js file:
'use strict'
const express = require('express')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const keys = require('../../../../config/keys')
const passport = require('passport')
const status = require('http-status-codes')
const User = require('../../models/User')
module.exports.test = (req, res) => {
res.json({msg: 'Users works'})
}
module.exports.userRegister = (req, res) => {
// Function implementation here
}
Lastly, I have written some test cases in userController.test.js:
'use strict'
const mongoose = require('mongoose')
const testUserDB = require('../../../config/keys').testUsersMongURI
mongoose.connect(testUserDB)
const userController = require('../modules/controllers/userController')
const User = require('../models/User')
// Test description and implementation
describe('register new user', () => {
test('succesfully register a valid user', () => {
// Test case details
})
})
The command I use to run the tests is:
"test": "jest --coverage",
As a beginner in Javascript and Full stack development, I encountered an error that I find confusing. Here is the error message:
Error message displayed during test execution
Your assistance in resolving this issue would be greatly appreciated!