Unit testing an API built with Express and Mongoose using Jest

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!

Answer №1

userRegister function does not return a promise, so make sure to use .then for chaining purposes. It is recommended to save the returned value in a variable and perform necessary checks on that value.

let registeredUser = userController.userRegister(req)
expect(registeredUser.name).toBe('test')
expect(registeredUser.email).toBe('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="12345678901234567890">[email protected]</a>')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a specialized angular controller

Is there a way to create a custom controller programmatically while preserving scope inheritance? I am looking to achieve something similar to this: var controller = 'myCtrl'; var html = '<p>{{value}}</p>'; var validScope= ...

Is it possible for JavaScript to only work within the <script> tags and not in a separate .js

I'm facing a puzzling issue with my JavaScript code. It runs fine when placed directly within <script>...code...</script> tags, but refuses to work when linked from an external file like this: <SCRIPT SRC="http://website.com/download/o ...

Issue with Firefox not recognizing keydown events for the backspace key

I am currently developing a terminal emulator and have encountered an issue with capturing the backspace key in Firefox. While I am able to capture the first backspace press and delete the last character in the input prompt, the problem arises when trying ...

Struggling to validate jest snapshot matching

I've been struggling with this issue for a few days now. I can't seem to get the '.toMatchSnapshot' test to pass, and it's clear that I'm missing something in my understanding of how it works. Should I be making changes to my ...

Mastering NodeJS Promises: Efficiently Handling Multiple http.get Requests

I have recently started learning about NodeJS and Promise functionality, so please be patient with me if this question seems uninformed. My goal is to first retrieve a database of records and then verify that the links associated with these records return ...

Allusion to a intricate data component

In my code, I have a model that is being represented by a class. For example, let's consider the model of a car: export class Car { public name : string; public color: string; public power : number; public service : boolean; } All c ...

An HTML form featuring various submit buttons for accomplishing different tasks

After searching extensively, I have come across solutions that are similar but not quite right for my specific situation. Here's what currently works for me: <script type="text/javascript"> function performTask1(a, b) { window.open('intern ...

What steps can I take to condense and tidy up this output into a more compact string?

Recently, I've been experimenting with Google's APIs and attempting to create a terminal command that can inform me of the distance and travel time to a particular location. However, I'm running into an issue with the current output format: ...

Troubleshooting: AngularJS not displaying $scope variables

I have a question that has already been answered, but the suggested solutions did not work for me. Everything seems to be fine, but the content within curly brackets is not displaying on screen. <div ng-controller="Hello"> <p>The I ...

Refreshing HTML Form upon Submit using JavaScript

I've been searching through various discussions without any luck, but I'm encountering an issue with a form that successfully submits data to a Google Sheet, yet the input fields retain their content after submission. Here is the code: <form ...

Omit node_modules from typescript compilation using gulp-typescript

Having trouble running a gulp task to compile my typescript due to dependency-related errors. /content/node_modules/@angular/core/src/facade/lang.d.ts(12,17): error TS2304: Cannot find name 'Map'. /content/node_modules/@angular/core/src/facade/l ...

"Using findByIdAndUpdate does not result in any updates being made

I'm currently following a tutorial that seems to be outdated, as there have been changes made. I am working on an edit page for editing existing data in MongoDB, but I can't seem to get it to work. Here is what the tutorial instructed: app.put( ...

Can transitions be applied to links in this manner?

Having an issue with ajax requests, I am currently resorting to using JavaScript linking. This is how I normally link: window.location.href = ('file:///android_asset/www/custom/kontakty.html'); I am curious if it's possible to add a transi ...

Transferring Data from Controller to HTML in AngularJS Version 1

Recently, I started working with angularjs on a new project that involves three main HTML files. The first file is index.html, which contains the ng-view directive. The second file is home.html, where various products are displayed from a database. Each pr ...

Receiving partial data through the API

My PHP API seems to be experiencing issues when I send data to it using either a post or get request. The strange thing is that the API receives only half of the data. This API functions perfectly fine on localhost, but encounters errors when used on the p ...

Having difficulty retrieving values while using async-await

Utilizing the code below has been successful for me. I managed to retrieve the data in the spread (then), returning a http200 response. Promise.all([ axios({ method: 'post', url: 'https://oauth2.-arch.mand.com/oauth2/token&a ...

Switch up the color of checkboxes with a dropdown menu option

I have an HTML dropdown code and I am trying to trigger a click event when a specific value is selected. Once this value is clicked, I want some checkboxes to change color. <select> <option value="calculate">calculate</option> ...

What is the best way to animate elements so that they move in a circular motion?

My goal is to recreate the image shown in the picture: https://i.sstatic.net/z08II.jpg In case the image is blocked, you can view it here: https://i.sstatic.net/YYg4J.jpg The picture appears to have only one icon visible, but there are actually 4 icons. ...

Tips on maximizing efficiency in number game coding

Seeking to create a number using a specified set of 6+ inputs. For instance, aiming for the number 280 with inputs [2,4,5,10,30,50,66], the desired output format would be something like this: ((2+5) * 4 * 10). Each input number can only be used once per s ...

Having trouble with Angular 2+/NodeJS/Express routing after refreshing the page?

Initially, I believed this issue to be specific to Heroku, but it persists even when running the application locally with NodeJS. The main page of my Angular app loads perfectly, and the routes function correctly when navigating through the links provided ...