2

I am coding a test file to test a backend written in Express with jest but what I can't understand is how Node JS manage the export of function with parameters. I have the following code:

function checkCredentials( u, p)
{ 
     var check = false;
     if((vectorUsr.indexOf(u)!= -1) && (vectorPswrd.indexOf(p) != -1))
     {
          check = true;
     }
     return check;
}
app.post('/home', function(req, res)
{
    if(checkCredentials(req.body.username, req.body.password))
    {
        req.session.success=true;
        console.log(req.body.username + " submitted Successfully!");
        console.log("POST HOME");
        res.status(200).render('home',{success: req.session.success});
    }
    else
    {
        req.session.success = false;
        res.status(403).redirect('/login');
    }
});

At the end of the file I have added these two lines to do the test:

exports.checkCredentials = checkCredentials(u,p);
module.exports = app;

On the test.js (user and password string are values contained in the vectorUser and vectorPswrd) I have written:

    describe(' Login', () =>
    { test(' POST request', (done) =>
      { 
           request(app).post('/home').then((req) =>
           {
                expect(app.checkCredentials('user', 
                'password')).toBe(true).then((res) =>
                {
                     expect(res.statusCode).toBe(200);
                     done();
                })
           })
       })
   })

But when I run jest --runInBand the console says

ReferenceError: u is not defined

  60 |     }
  61 |     else
> 62 |     {
  63 |         //Ritorno alla pagina di login
  64 |         req.session.success = false;
  65 |         res.status(403).redirect('/');

I really don't understand why this error appears

1 Answer 1

1

In this section you are referring to a variable u:

vectorUsr.indexOf(u)

But u is not defined anywhere.

I expect you intended:

if((vectorUsr.indexOf(user)!= -1) && (vectorPswrd.indexOf(pswrd) != -1))
Sign up to request clarification or add additional context in comments.

2 Comments

I have made typo while I was writing the question sorry, now the script of the question is correct
Ah. I notice that the ReferenceError does not correspond to the code. I suspect one is out of date. Can you update one or the other to make sure the error message is consistent with the code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.