Creating unit tests for a javascript method that employs a JWT token

Currently, I'm facing a challenge when writing unit tests in JavaScript for a method that includes JWT token validation. The method should only fetch results if the token is valid.

I'm looking to mock the JWT token and return results. I've attempted using the Ava test framework, mock require, and Sinon, but unfortunately, I've been unsuccessful so far.

Do you have any suggestions on how to achieve this?

Code:

Trying to mock jwt.verify    

**unit test:**

const promiseFn = Promise.resolve({ success: 'Token is valid' });

mock('jsonwebtoken', {
        verify: function () {         
            return promiseFn;   
        }
});

const jwt = require('jsonwebtoken');

const data =  jwt.verify(testToken,'testSecret');

console.log(data)


**Error :**

ERROR
    {"name":"JsonWebTokenError","message":"invalid token"} 


The issue at hand is that the token is being verified, but the mock is not being invoked.

Answer №1

In Node.js, modules are treated as singletons. This means that if you require a module like 'jwt' in your test and then require it again in your business logic, it will refer to the same object.

Therefore, you can require the 'jwt' module in your test and then mock the verify method.

It's also crucial to remember to restore the mock after the test is completed.

Below is a simple example demonstrating how you can achieve this using ava and sinon:

const test = require('ava');
const sinon = require('sinon');
const jwt = require('jsonwebtoken');

let stub;

test.before(t => {
    stub = sinon.stub(jwt, 'verify').callsFake(() => {
        return Promise.resolve({success: 'Token is valid'});
    });
})

test('should return success', async t => {
    const testToken = 'test';
    const testSecret = 'test secret';

    const result = await jwt.verify(testToken, testSecret);

    console.log(result);

    t.is(result.success, 'Token is valid');
});

test.after('cleanup', t => {
    stub.restore();
})

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

Linking model attribute to checkbox in AngularJs

Currently, I am working on assigning tags during post creation. For this purpose, I have set up a Post model with the following structure: var mongoose = require('mongoose'); var PostsSchema = { title: String, content: String, poste ...

The request payload appears as [Object Object] when initiating the AJAX post request

Currently, I am making an AJAX request with the specified data. The data being sent is an object and my intention is to send the object itself without converting it to a JSON string. However, when viewing the request in the browser, the payload is shown as ...

How to access and retrieve selected checkbox values using jQuery

<form id="myform"> <input type='checkbox' name='foo[]' value='1'> <input type='checkbox' name='foo[]' checked='true' value='2' > <input type='checkbox' ...

AngularJS version 1.5.11 experiencing issues with ng-repeat functionality

Having an application built on angularJS v1.5.11, I encountered a major issue while attempting to use ng-repeat in a table format like below: <tbody> <tr ng-repeat="score in data.result"> <td ng-repeat="item in score"> {{ item }} & ...

Is jQuery AJAX returning improperly formatted JSON when using the jsonp type?

$('#rn_s').keyup(function() { var rn = $('#rn_s').val(); if(rn.length == 9) { $.ajax({ url: 'http://routingnumbers.info/api/data.json?rn=' + rn, type: 'GET', dataT ...

Exploring the intersection of JavaScript and PostgreSQL: Leveraging timezones and timestamps

I'm a bit confused about how to properly use timestamps. For example, when a user creates an article, they can choose a PublishDate, and the system also automatically stores a CreateDate. a. Should I make both PublishDate and CreateDate timestamps wi ...

Leverage ajax/js to dynamically refresh a single select tag within a set of multiple

While working on a project, I encountered a challenge while using JavaScript to update a <select> tag within a page. The specific issue arises because the page is designed in a management style with multiple forms generated dynamically through PHP ba ...

When information is provided, record the values in a separate input field

I'm struggling to come up with an appropriate title... Here's the issue: if a user inputs anything into the "Accompanying Person" field, the "Accompanying Person Price" field will automatically be set to 260€. I have no clue on how to achieve ...

Tips for ensuring that the toJSON method in Sails.js waits for the find operation to complete before returning the object

When I try to run a find inside the toJSON function in the model, the object is returned before the find completes. How can I ensure that the return happens only after the find operation has completed? toJSON: function() { var obj = this.toObject(); Com ...

display object issue with object display

I'm encountering a strange issue with my constructor objects in JS - when I try to view them, all I see is [object Object]. Can anyone help me figure out why this is happening? Check out the code snippet on MyCodeFiddle. ...

A guide on clearing the selected value in a dropdown menu with Angular.js

Can someone assist me with setting the drop-down value to blank after completing an action in Angular.js? Below is my code explanation: <div style="height:270px; overflow-x:hidden; overflow-y:scroll;" ng-show="viewOrderTable"> <div class="table-r ...

Creating a fluid side navigation bar in reactjs

Can someone please help me with the following code issue? I am encountering an error related to the script tag when running it in ReactJS, although it works fine in a simple HTML file. Upon starting npm, an error is displayed pointing to line number which ...

Substituting JSON objects with alphabets

When running this code, the expected output will display the name and the choices. To clarify, I aim to substitute the values of Not effective, Neither effective nor Effective, Effective with "A", "B", and "C", respectively. ...

Change background according to URL query

My goal is to dynamically change background images based on a URL parameter, specifically the destination code. With numerous background images available, it's crucial to display the correct one depending on the URL string. For instance, if the URL re ...

How can I trigger an Onclick event from an <a tag without text in a Javascript form using Selenium?

Here is my original source code: <a onclick="pd(event);" tabindex="0" issprite="true" data-ctl="Icon" style="overflow: hidden; background: transparent url("webwb/pygridicons_12892877635.png!!.png") no-repeat scroll 0px top; width: 16px; height: 16px ...

How can I iterate through JSON data and showcase it on an HTML page?

I am in the process of developing a weather application using The Weather API. So far, I have successfully retrieved the necessary data from the JSON and presented it in HTML format. My next goal is to extract hourly weather information from the JSON and ...

Using JavaScript, import the variable module object from a specific module

Is there a way to import a module object from a module if I am unsure of the specific objects I will need beforehand? How can I utilize a variable in place of fixed module names? import { dynamicVariable } from './module' The variable represents ...

pressing the downward arrow does not cause the number to decrease

I'm facing an issue with my code in this video. The increment is working when the upward arrow is clicked, but not the decrement. I suspect there's a problem with the jQuery code. Initially, I tried modifying from top to bottom, and changing +1 t ...

Is there a way to alter the background color of a Material UI card when it is being hovered over

I'm currently using material ui with react and I have a question regarding the background color of my card component when a user hovers over it. Can someone help me figure out how to achieve this? For reference, here is the live code link in CodeSand ...

Having trouble transferring ASP server control value to a Javascript function

Currently working with ASP.NET 2.0. My Entry Form contains various ASP.NET Server Controls, such as TextBoxes. I want to pass the value of a TextBox on the onBlur event. Here is an example of a TextBox code: <asp:TextBox ID="txtTotalTw" Width="80px" r ...