Verifying API functionality with a mocha test for the PUT endpoint

My mocha test is producing an error message: "Uncaught AssertionError: undefined == 'Ernest'. It seems like the test may be referring to the song instance created at the beginning of the code. I'm unsure about how to resolve this issue.

This API is designed for a MEAN stack application, using mongoose as the ODM.

test.js

it('can save a song', function(done) {
        Song.create({ title: 'saveASong' }, function(error, doc) {
            assert.ifError(error);
            var url = URL_ROOT + '/create/song/saveASong';
            superagent.
                put(url).
                send({
                    title: 'saveASong',
                    createdBy: 'Ernest'
                }).
                end(function(error, res) {
                    assert.ifError(error);
                    assert.equal(res.status, status.OK);
                    Song.findOne({}, function(error, song) {
                        assert.ifError(error);
                        assert.equal(song.title, 'saveASong');
                        assert.equal(song.createdBy, 'Ernest');
                        done();
                    });
                });
        });     
    });

Custom route:

//PUT (save/update) song from the create view
    api.put('/create/song/:title', wagner.invoke(function(Song) {
        return function(req, res) {
            Song.findOne({ title: req.params.title}, function(error, song) {
                if(error) {
                    return res.
                        status(status.INTERNAL_SERVER_ERROR).
                        json({ error: error.toString() });
                }
                song.save(function(error, song) {
                    if(error) {
                        return res.
                            status(status.INTERNAL_SERVER_ERROR).
                            json({ error: error.toString() });
                    }
                    return res.json({ song: song });
                });
            });         
        };
    }));

UPDATE: After adding a console.log(res.body) right after "end", the response did not include the "createdBy: Ernest" key-value pair. I attempted to change another key-value pair in the object being sent, but it still didn't persist. There are no errors when I remove the "assert.equal...'Ernest'" line.

Revised version of PUT route:

api.put('/create/song/:title', wagner.invoke(function(Song) {
        return function(req, res) {
            Song.findOneAndUpdate({ title: req.params.title}, req.body ,{ new: true }, function(error, song) {

                if(error) {
                    return res.
                    status(status.INTERNAL_SERVER_ERROR).
                    json({ error: error.toString() });
                }

                return res.json({ song: song });
                });
        };          
    }));

Answer №1

the following endpoint is used for creating a song in the API

api.put('/create/song/:title', wagner.invoke(function(Song) {
        return function(req, res) {
            Song.findOneAndUpdate({ title: req.params.title}, req.body ,{ new: true }, function(error, song) {

                if(error) {
                    return res.status(status.INTERNAL_SERVER_ERROR).json({ error: error.toString() });
                }

                return res.json({ song: song });
            });
        };          
    }));

this mocha test verifies that a song can be successfully saved using the API

it('can save a song', function(done) {
        Song.create({ title: 'saveASong' }, function(error, doc) {
            assert.ifError(error);
            var url = URL_ROOT + '/create/song/saveASong';
            superagent
                .put(url)
                .send({
                    sections:[{ name: 'intro', timeSig: 140 }]
                })
                .end(function(error, res) {
                    assert.ifError(error);
                    assert.equal(res.status, status.OK);
                    console.log(res.body);
                    Song.findOne({}, function(error, song) {
                        assert.ifError(error);
                        assert.equal(song.title, 'saveASong');
                        assert.equal(song.sections[0].name, 'intro');
                        done();
                    });
                });
        });     
    });

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

Error: Unable to set attribute because the property is undefined in the onLoad function

Can anyone help troubleshoot this error? List of included files: <link rel="stylesheet" href="../../node_modules/semantic-ui/dist/semantic.min.css"> <link rel="stylesheet" href="../../node_modules/font-awesome/css/font-awesome.min.css"> <l ...

The startOf function in moment.js is functioning properly, however the endOf function is returning an

Hey there, I was attempting to retrieve the start and end date of a specified month using Moment.js. Here is the code snippet I used: //function to get the ranges of month specified function Calculate() { // get entered month const month = docum ...

Observable not defined in facade pattern with RxJS

(After taking Gunnar's advice, I'm updating my question) @Gunnar.B Tool for integrating with API @Injectable({ providedIn: 'root' }) export class ConsolidatedAPI { constructor(private http: HttpClient) { } getInvestments(search?: ...

Keep the submenu visible upon clicking the sign-in form / Adjust the background color when the parent li is selected

I am facing two issues with my navigation menu that has dropdown lists: When clicking on a parent li, its submenu is displayed, but it gets hidden when clicking on another parent li or anywhere else on the page. For the first li.parent which contains a ...

Troubleshooting: jQuery toggle() issue in Firefox 3.0.12

My jQuery code for toggling is working perfectly in IE6 but not in FF3. I'm wondering what could be causing this issue and if there is a workaround available. <button>Toggle Me</button> <p>Hi</p> <p>Learning jQuery&l ...

Is there a way to modify or add to the response object's methods in Express and Node.js?

When using middleware in Express, the framework passes both a res and a req object. These objects enhance the built-in ones from http.ServerResponse and http.ClientRequest respectively. I am curious about the possibility of overriding or extending methods ...

What strategies should be employed to manage data-driven input in this particular scenario?

In the process of creating a small webpage, I have designed 2 navigation panels - one on the left and one on the right. The leftNav panel contains a list of different flower names. While the rightNav panel displays images corresponding to each flower. A ...

Encountering MIME type error (text/html) during Angular project deployment

I am facing an issue while trying to deploy a project built with Angular/CLI 6.12.0. After transferring the content of the "dist" folder to a server, I encountered a console error related to MIME type. The module at address "http://www.sylvainallain.fr/p ...

Can Puppeteer extract the complete HTML content of a webpage, including any shadow roots?

When using Puppeteer to navigate a webpage, I typically can retrieve the full HTML content as text with this code: let htmlContent = await page.evaluate( () => document.querySelector('body').innerHTML ); However, I am currently faced with ...

The issue of receiving a 500 error when making a POST request in node.js

I have created my own unique REST API that utilizes an NLP API internally. I need to post data on their URL, but unfortunately I am encountering an error that is causing my API to return a 500 error to the frontend. Below is a snippet of my server.js code ...

JavaScript/jQuery countdown timer failing to initialize properly

Having some trouble with a countdown timer that I customized from the original version. The issue seems to be with startCountdown(startDate,deadlineDate,expiredText) as it's returning undefined. Any thoughts on what might be causing this? All relevan ...

Issue in Jquery: Unable to load the corresponding pages when toggling the checkbox on and off

I am facing an issue with a checkbox and calling different php pages based on the status of the checkbox. Currently, the code works only for checked checkboxes. I'm not sure why it's not working for unchecked checkboxes as well. <script type ...

Send a file from a form using Gatsby to getform.io using the axios library

I am facing an issue with my getform.io form where the file is not getting uploaded properly. The file appears as [] and the files tab remains empty. Upon checking the network tab, I noticed that my request payload includes {email: "[email protec ...

Validate two schemas with Joi conditionally - Schema content is invalid

I am currently working on implementing a conditional schema based on the value of the isCat field in the request body. However, I keep encountering an error that says 'ror [ERR_ASSERTION]: Invalid schema content'. Any ideas on what might be causi ...

Flipping and expanding cards with CSS3

I am attempting to create a layout with a collection of cards/divs within a container. When a card/div is clicked, it should flip horizontally and expand to occupy the entire space within the container (essentially resizing to 100% x 100% when clicked). I ...

Loading SVG templates dynamically in Angular can be done by utilizing a string

Is it possible to convert SVG content loaded from a server into a component template in Angular, with the ability to bind properties to it? For example, <tspan [attr.color]="textColor" ...>{{myText}}</tspan>. I have tried loading and ...

The user login validation with regex seems to be malfunctioning

I am trying to ensure that the user login input only contains Latin and Russian letters, digits 0-9, and some specific symbols like dots. I have attempted using regular expressions for validation but so far none of them have been successful. errors["error ...

Error: Unable to locate module adaptivecards-templating

After adding the module through the command: npm install adaptive-expressions adaptivecards-templating --save and importing it, I encountered an error when trying to run my application: ...

steps for executing a Google script

In my program, the structure is as follows: // JavaScript function using Google Script 1. function F1() { ...... return (v1); } // HTML code for Google 1. <script> 2. function F2() { 3. alert ( 1 ); 4. function F2(); 5. alert ( 2 ); 6 ...

Conceal overflow in SVG after stroke is applied to top rectangle border

Is there a way to conceal the overflowing red color in this SVG? I attempted repositioning it before the rect with the stroke, but that didn't solve the issue. Check out the code and screenshot below. <br><br> <svg _ngcontent-fdl-c1 ...