simulate express-jwt middleware functions for secure routes

I am currently facing an issue with my code snippet, which looks like this:

import app from '../src/app';

beforeAll(() =>
  jest.mock('../src/middleware/auth', () => (req: Request, res: Response, next: NextFunction) => {
    req.user = {};
    return next();
  });

afterAll(() =>
  jest.unmock('../src/middleware/auth'));

Following that, I have my test set up as usual:

describe('POST /v1/protected-route', () => {
  it('should return 200 OK', async () => {
    await request(app)
      .get('/v1/protected-route')
...

In my ../src/app file, I import ./middleware/auth and add it using app.use(auth()).

Despite these efforts, I continue to receive 401 errors, indicating that the mock is not being utilized correctly in this context.

Answer №1

After encountering a similar issue, I found a solution by relocating the jest.mock() outside of the beforeAll() block. It seems that the jest.mock() declaration is scoped to its surroundings, rather than the entire file. This explains why importing your app at the top of the file (along with requiring middleware) results in the original middleware being used instead of the mocked one within the beforeAll() function.

Being new to jest, there may be some important details I am missing...

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

Execute an Asynchronous Operation in NgRx After Triggering an Action

Please note that this is a question seeking clarification Instructions Needed I am currently working on dispatching an action to NgRx in order to add a task to a list of tasks. Additionally, I need to perform a put request to an API to save the changes ma ...

Struggling with setting up routes in Express and React - need help troubleshooting!

Currently in the process of learning Express/React and attempting to configure routes and establish basic database connections. I have a hunch that I am overlooking something simple. Below is a condensed version of the setup I am working with. Backend se ...

Converting JSON data into clickable URL links and retrieving information upon clicking

I have a dataset in JSON format. As I iterate through it, I'm inserting selected values into an HTML link element as shown below: getPatchList: function() { $.ajax({ url: "/returneddata" }).done(function(r ...

Using Angular 2 to assign a function to the ngClass directive within the template

I've been searching for a solution to this issue, but so far nothing has worked for me. When I try to pass a function to the ngStyle directive, I encounter the following error: The expression 'getClass()' in ProductView has changed after i ...

Initiate asynchronous ngOnInit

Can ngOnInit() actually return a promise? I've noticed a common practice where developers use this approach and it appears to be functional. However, there is a risk with unobserved promises as they can be resolved or rejected at unexpected times, s ...

Issue: req.flash() not functioning correctly following the execution of req.session.destroy()

In order to log the user out and redirect them to a login page with a message under specific conditions, it is necessary to destroy the user's current session. I usually use the flash feature to display a one-time message in my application, which work ...

The attempt to add a new task using the `todos.insertOne()` function did not successfully complete within the allotted 10,

I was working on a basic todo list, but every time I try to run it and refresh the page, an error occurs. Here is the code snippet: import mongoose from "mongoose" import express from "express" import { Todo } from "./models/Todo.j ...

Utilizing NGRX reducers with a common state object

Looking for a solution with two reducers: export function reducer1(state: State = initialState,: Actions1.Actions1); export function reducer2(state: State = initialState,: Actions2.Actions1); What I want is for both reducers to affect the same state objec ...

My React higher order component implementation is revealing the protected route momentarily

import { useRouter } from "next/router"; import { useEffect } from "react"; import axios from "axios"; export default (ChildComponent) => { const enhanceComponent = (props) => { const router = useRouter(); co ...

The only thing you can see in MongoDB output is the objectid

Trying to save data in mongodb using an open schema. After making a post request, the only thing showing up in the database is the objectid. As someone new to MongoDB and Node.js, I'm struggling to identify where my mistake lies. // <---------se ...

What is the best way to create a personalized filter function for dates in JavaScript?

I am working with a DataTable that includes a column called Timestamp: <p-dataTable sortMode="multiple" scrollable="scrollable" scrollHeight="150" [value]="currentChartData" #dt> <p-column field="timestamp" header="Timestamp" [sortable]=" ...

Uploading files to AWS S3 with Node.js - dealing with file corruption

I have been working on uploading a file to an S3 Bucket using nodejs express. This is the code I have implemented: HTML Here, I am uploading the file using Jquery formData <form id="form" action="" method="post" enctype="multipart/form-data"> ...

"Error: The method setValue is not found in the AbstractControl type" when trying to clear form in Angular 2

Here is the template code: <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" novalidate="novalidate"> <textarea [ngClass]="{ 'error': comment }" [formControl]="form.controls['comment']" ...

Testing the controllers in Express is crucial for ensuring the functionality

When it comes to unit testing with Express, I've been facing some challenges due to the lack of documentation and information available online. I have discovered that I can test my routes using a library called supertest (https://github.com/visionmed ...

How can I store various data types in a single array in TypeScript?

I have a scenario I need help with. Let's say we have two interfaces, Cats and Dogs. How can I create an array that can store both Cats and Dogs? interface Cats { name: string; age: number; } interface Dog { owner: string; } const cat1: Cat ...

Getting started with Angular 2 using NPM version 3.10.6 and Angular CLI 1.0.0

I am having trouble when I run 'NPM start,' all I get is https://i.sstatic.net/QCViF.png Below are the files in my project: package.json { "name": "angular2-quickstart", "version": "1.0.0", // rest of the package.json file continues... } ...

Leveraging the power of Next.js and a tailored deployment strategy using Express and Node

Recently, I encountered an issue while trying to deploy my app that utilizes Next.js on the frontend (including some getStaticProps function) and a custom express/node.js backend on Azure. The backend is connected to MySQL, although I don't believe th ...

Unit testing Jest for TypeScript files within a module or namespace

Recently, I've joined a mvc.net project that utilizes typescript on the frontend. There are numerous typescript files wrapped within module Foo {...}, with Foo representing the primary module or namespace. All these typescript files are transpiled in ...

Exploring the Concept of Template Element Recursion in Angular JS 2

In my Angular 2 project, I encountered a situation where I needed to iterate through ngFor based on child elements. My component should be able to render a list based on the input provided. Here is an example of the data structure: [ { name: 'ABC ...

Utilize Expressjs to send responses in both JSON and XML formats

My current task involves generating JSON and XML output from a database dataset. Here is my Express code for generating a JSON response: var express = require('express'), async = require('async'), http = require('http&ap ...