Exploring the capabilities of jasmine-node

Let's set up a test scenario:

An authenticated user wants to update the description of a 'module' attribute. The 'module' data is not stored in a database but rather defined in a required file.

Below is the test code that needs fixing:

First, we have a helper function for logging in: //app.spec.js

var login = function(done) {
    var options = {
          uri: 'http://localhost:3000/login'
        , method: 'POST'
        , form: {
              username: 'user'
            , password: 'ffff'
        }
    }
    request(options, function() {
        done();
    });
};

Followed by the actual test case:

it('should be able to change the description of a module', function(done){
    login(done);
    var options = {
          uri: 'http://localhost:3000/module/1'
        , method: 'POST'
        , form: {
            desc: 'test'
        }
    }

    request(options, function(err, res, body){              
        var modules = require('../Model/module').modules;
        console.log(modules);
            expect(modules[0].desc).toBe('test');
            done();
    });
});

Lastly, here's the endpoint logic in app.js:

app.post('/module/:module_id', ensureAuthenticated, function(req, res) {    
    var desc = req.body['desc'];
    if(req.module_id){
        findModuleById(req.module_id, function(err, module) {
            module.desc = desc;
            console.log('changed module');
            console.log(module);
        });
    }

    res.redirect('/');
});

The issue arises when checking console.log(modules) from app.post as it reflects the correct value 'test', but the test still fails with the default value.

If anyone familiar with writing tests in express/node has any suggestions, please do share. Your insight would be greatly appreciated.

P.S. Here are the current module details:

//Model/module.js

    var modules = [
      {id: 1, desc: 'Default description for module 1'}
    , {id: 2, desc: 'Default description for module 2'}
    , {id: 3, desc: 'Default description for module 3'}
    ];

module.exports.modules = modules;

Answer №1

In my opinion, it would be more appropriate not to pass the jasmine-node supplied done callback to the login function. Instead, you should pass a separate function that will execute the rest of your test.

it('should be able to change description of a module', function(done){

    var onDoneLoggingOn = function(){
        var options = ...
        request(options, function(err, res, body){              
           ...
           done();
        });
    };
    login(onDoneLoggingOn);
});

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

What is the proper way to send an AJAX request with the data type set to

I am currently working on creating my own POST request. Below is the function I have written: function sendPost(o) { var h = new XMLHttpRequest(); h.onreadystatechange = requestComplete; function requestComplete() { if (h.readyState = ...

Vue.js 2 components encountering issue with parent-child relationship due to undefined item

I recently started working with Vue and encountered the error referenceError: items is not defined. Can anyone help me figure out why this error is occurring or provide some guidance? Upon initial inspection of the code, it seems like the issue may be rel ...

"Using a triangular background shape in JavaScript instead of a traditional circular

I want to add a unique effect to my site inspired by the AnimatedHeaderBackgrounds demo available at this link. My twist on this effect involves using upward-moving triangles instead of circles. I've explored various resources, including Stack Overfl ...

The function "getElementsByClassName" in Javascript is malfunctioning

I have redesigned my website by implementing an interactive feature where users can click on a tree image to remove it and replace it with a number using JavaScript. Initially, I targeted the specific tree with the following code: document.getElementById( ...

Sequencing the loading of resources in AngularJS one after the other by utilizing promises

While working in a service, my goal is to load a resource using $http, store it in a variable, load a child resource and store that as well. I understand the concept of promises for this task, but I am struggling with how to properly implement it in my cod ...

Error: Trying to access undefined properties and using the map function on an incorrect element in NextJS and React

Utilizing NextJS and the getServerSideProps function to retrieve data from a Prisma database has worked flawlessly in my development environment. However, upon deployment with Vercel, I have encountered persistent issues. This is the approach I took: I f ...

Syntax for chained arrow functions

const retrieveData = link => dispatcher => { // ... } export const fetchInfo = searchTerm => (dispatcher) => { return dispatcher(retrieveData(searchTerm)); }; What role does dispatcher play in the retrieveData function? Is link the only p ...

Encountering an issue in Angular 8 where there is a difficulty in reading the property 'NODE_NDEBUG' when attempting to serve the application

An issue has been identified in the assert-plus library at ../node_modules/assert-plus/assert.js where it is encountering difficulties reading 'NODE_NDEBUG' from 'process.env', as highlighted in the code snippet below module.exports = ...

The jQuery progress bar vanishes once .load() is employed

I have successfully implemented progress bars on my website. However, I am facing an issue when I reload the div using jQuery's .load() function. After the div is reloaded, the progress bars disappear, although everything else seems to be functioning ...

JQuery selecting and highlighting a row within a dynamically loaded table via ajax

On a webpage, there are two tables being displayed. The first table loads along with the entire page, while the second table is loaded later on using ajax. Each row in both tables contains links. Upon clicking a link, the corresponding row in the table ...

Getting an error that reads, "Unable to read properties of null (reading 'uid')," but surprisingly, the application continues to function properly

After logging out, I encounter the following error: (Uncaught TypeError: Cannot read properties of null (reading 'uid')). However, my application functions as intended. During the logout process, I delete an API access token from the user docume ...

Vue is set up to monitor changes in two connected input fields for user input exclusively

Two input fields are available, where the value of one can affect the other. If a value between 1 and 200 is entered in the level field, Vue will look up the corresponding points for that level and populate the points field with them. Conversely, if a us ...

What steps can be taken to resolve the error message "t.onSubmit is not a function" that occurs upon form submission?

Upon submitting a form, it should trigger the onSubmit method function. However, an error is being returned instead: TypeError: "t.onSubmit is not a function". I've attempted to address this issue by researching similar problems and solutions provide ...

Verify if session is in existence

Currently in the process of setting up my NodeJS and Express App, utilizing Passport for authentication through Google Sign In and Login. All functionalities work flawlessly when tested on localhost. The sign-in process is smooth, and upon checking, I can ...

Discover the dynamic method for determining the value of a nested array based on a specific condition

Currently, I am delving into the world of nested arrays and attempting to locate a specific value within the array based on a condition. The data returned by the API is structured in the following format: data= { "ch_Id": "1234", "title": "Title" ...

"Exploring three.js: How to locate the closest point on a Mesh to the position of

In this scenario, picture a three.js scene configured with an OrthographicCamera and OrbitControls: https://i.sstatic.net/rhJnr.png When the user moves the yellow disc (representing the Sun), it should follow along its corresponding yellow circle. To bet ...

The fetch() function is inundating my API with an overwhelming amount of requests

After implementing the following function to retrieve images from my API, I encountered an issue: function getImages() { console.log("Ignite"); fetch('https://api.itseternal.net/eternal/stats', { headers: { & ...

Create an animated A-frame box that moves randomly within a designated space

Looking to add some movement to my A-frame scene with a random box animation. I want to utilize the animation property to make an entity move randomly within a specified area. The goal is to have a box animate to a random position within coordinates rang ...

How to extract only the truthy keys from an object using Angular.js

I am looking to retrieve only the keys with a true value in the data object and display them in the console with the specified format: Object { Agent=true, Analytics / Business Intelligence=true, Architecture / Interior Design=false } The catego ...

selecting a radio button and saving its value into a JavaScript variable

How can I assign the return value from a JavaScript script function to a variable inside the HTML body? The function will return the selected variable, but how can I assign it to a variable within my HTML body? <body> <form action="somepage.php ...