N
N
Nick_Name12018-11-29 19:17:36
JavaScript
Nick_Name1, 2018-11-29 19:17:36

How to modularize code for unit testing in Node.js, how to replace lambdas with named functions?

Good afternoon. For coursework on unit testing, I needed to quickly write an API server, because I wanted to devote more time to the Android client, so I chose Node.js. Before that, I didn’t write anything on it, and I didn’t touch javascript too much. I found a guide, did everything according to it, but now I need to test my code. I can immediately test a POST request that will call this method and compare the server response with the expected one, but it seems to me that the code is cumbersome and is responsible for different logic, I think it should be divided into methods and tested as separate modules, and then tested POST request, then, as I understand it, this will already be integration testing, since several modules are tested at a time.
The question is, how do I break this code up, since I don't really understand the function syntax, how can I best convert my lambdas into named functions and call them in the same places? At the same time, I would like to hear a couple of tips on how not to do it or what I'm wrong about.
I would like to see on a specific example how to deal with this piece of code, for example:

The code
exports.user_login = (req, res, next) => {
      console.log(req.body);
      User.find({'contacts.email': req.body.email})
        .exec()
        .then(user => {
          if (user.length < 1) {
            return res.status(401).json({
              message: "Auth failed"
            });
          }
          bcrypt.compare(req.body.password, user[0].password, (err, result) => {
            if (err) {
              return res.status(401).json({
                message: "Auth failed"
              });
            }
            if (result) {
              const token = jwt.sign(
                {
                  email: user[0].email,
                  userId: user[0]._id,
                  roles: user[0].roles
                },
                process.env.JWT_KEY,
                {
                  expiresIn: "10 days"
                }
              );
              return res.status(200).json({
                message: "Auth successful",
                token: token
              });
            }
            res.status(401).json({
              message: "Auth failed"
            });
          });
        })
        .catch(err => {
          console.log(err);
          res.status(500).json({
            error: err
          });
        });
    };

I use it for POST request: Any help would be greatly appreciated.
router.post("/login", UserController.user_login);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question