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

Is the accuracy of the in-situ convolution filter guaranteed?

After analyzing my simple box blur function, I have come to the realization that it may be incorrect. The current implementation edits the ImageData object in place, leading to convolution filters depending on surrounding pixels that have already been ch ...

Accessing Google Feed API to retrieve media thumbnails

I am currently utilizing the Google Feed API to extract a thumbnail from an RSS feed ("media:thumbnail") The media:thumbnail element in the RSS feed is structured as follows: <media:thumbnail url="http://anyurl.com/thumbnailname.jpg" width="150" heigh ...

What is the process for selectively adding interceptors to app.module?

After searching through various topics, I have not found a solution that addresses my specific issue. To provide some context, we have an Angular App that operates in two modes - one mode uses one API while the other mode utilizes a different API. My goal ...

A guide on transforming a JSON object representing an HTML element into a live HTML element for display on a webpage using C#, JavaScript, or jQuery

I am looking to retrieve a JSON object from a database and convert it into HTML format. Here is an example of the JSON structure: {"input":{ "name":"fname", "type":"text", "placeholder":"Ente ...

The dynamic import() syntax is not compatible with the target environment, preventing the use of external type 'module' in a script

I am currently facing an issue with my React app. The command npm start is working as expected, but when I try to run npm run build, it keeps failing. It's crucial for me to run npm run build in order to deploy the app on a website. I have already sp ...

How can I combine multiple styles using Material-UI themes in TypeScript?

There are two different styles implementations in my code. The first one is located in global.ts: const globalStyles = (theme: Theme) => { return { g: { marginRight: theme.spacing(40), }, } } export const mergedStyle = (params: any) ...

Problems encountered when transferring information from jQuery to PHP through .ajax request

Hey there! I am currently working with Yii and facing an issue while trying to pass some data to a controller method called events. This is how my jQuery ajax call looks like: var objectToSend = { "categories" : [selectedOption],"datefrom" : month + "" + ...

Conflicting events arising between the onMouseUp and onClick functions

I have a scrollbar on my page that I want to scroll by 40px when a button is clicked. Additionally, I want the scrolling to be continuous while holding down the same button. To achieve this functionality, I implemented an onClick event for a single 40px s ...

Vue Js: Creating an array of checkboxes

I have a collection of checkboxes sourced from the main system object where I store all system settings (referred to as getSystem{}). Within this form, I am retrieving information about a User, who possesses an array of roles []. How can I cross-reference ...

How to empty an array once all its elements have been displayed

My query pertains specifically to Angular/Typescript. I have an array containing elements that I am displaying on an HTML page, but the code is not finalized yet. Here is an excerpt: Typescript import { Component, Input, NgZone, OnInit } from '@angul ...

Let us know when the information on a different tab is updated

I have multiple tabs and I want to indicate when a change occurs on another tab that the user hasn't clicked. For example, if the user hits the run button while on the Data pane, I would like the Errors tab to change to red to show that there was a ch ...

What is the best way to send multiple variables to a url using jQuery ajax?

I am having trouble passing multiple values in the method below. Can someone help me with the correct syntax? I have attempted data: ('keyword='+$(this).val(),'id='10), as well as data: {'keyword='+$(this).val(),'id=&a ...

tag directive not functioning properly

I have encountered an issue while trying to create a simple custom directive. When I specify the directive as <div my-info></div> in my HTML file, it works fine. However, when I specify it as <my-info></my-info>, it does not work. ...

Inquiring about the Model component within the MVC architecture in a web application created with NodeJs and integrated with

As a beginner in NodeJs, I am venturing into creating web applications using the express framework and MySQL. Understanding that in MVC architecture, views are represented by *.ejs files, controllers handle logic, and models interact with the database. Ho ...

Tips for achieving expansion of solely the clicked item and not the whole row

I am trying to create a card that contains a cocktail recipe. The card initially displays just the title, and when you click on a button, it should expand to show the full menu and description. The issue I'm facing is that when I click on one element, ...

Exploring Angular 6 with Universal Karma for effective module testing

Issue I have been facing challenges while testing my Angular 6 application with Karma. I am encountering errors such as: Can't bind to 'ngModel' since it isn't a known property of 'mat-select'. Although the import works in ...

Is there a RxJS equivalent of tap that disregards notification type?

Typically, a tap pipe is used for side effects like logging. In this scenario, the goal is simply to set the isLoading property to false. However, it's important that this action occurs regardless of whether the notification type is next or error. Thi ...

Steps for loading a different local JavaScript file by clicking on a button

My goal is to reload the browser page and display a different ReactJS component/file when a button is pressed. Initially, I attempted using href="./code.js" or window.location="./code.js" within the button props, but unfortunately, it did not yield the des ...

Issue with Material UI Textfield functionality on mobile Safari browser

UPDATE: Resolved the problem by including this code in index.css input { -webkit-user-select:text;} In my application, I am using a Material UI box that contains text fields with an onChange handler. While the TextFields function correctly on most bro ...

The issue with the mongoose schema is that it is unable to properly store values for certain fields within the

Below is the schema provided: let tbljobsSchema = mongoose.Schema({ companyid:{type:mongoose.Types.ObjectId}, userid:{type:mongoose.Types.ObjectId,required:true,ref:'tblusers'}, jobtitle:{tyep:String,required:true}, category:{tyep:String,require ...