Categories
JavaScript Answers

How to unit test routes with Express and JavaScript?

To unit test routes with Express and JavaScript, we use supertest.

For instance, we write

describe("GET /users", () => {
  it("respond with json", (done) => {
    request(app)
      .get("/users")
      .set("Accept", "application/json")
      .expect(200)
      .end((err, res) => {
        if (err) return done(err);
        done();
      });
  });
});

to call request with app to use the Express app to make requests.

Then we call get to make a get request to the /users route.

We call set to set the request header.

We call expect to check that the status code returned is 200.

And we call end with a callback that calls done to finish the test.

The test passes if done is called with no argument.

Categories
JavaScript Answers

How to add dates to pm2 error logs with JavaScript?

To add dates to pm2 error logs with JavaScript, we add the --lof-date-format option.

For instance, we run

pm2 start app.js --log-date-format 'DD-MM HH:mm:ss.SSS'

to set the --log-date-format to the date format we want for the log entry date to include the date in each log entry.

Categories
JavaScript Answers

How to fix npm – “Can’t find Python executable “python”, you can set the PYTHON env variable.” error with JavaScript?

To fix npm – "Can’t find Python executable "python", you can set the PYTHON env variable." error with JavaScript, we install the window-build-tools package.

To fix this, we run

npm install -g windows-build-tools

to install the window-build-tools package globally which includes Python.

Categories
JavaScript Answers

How to fix the /usr/bin/env: node: No such file or directory error with Node forever?

To fix the /usr/bin/env: node: No such file or directory error with Node forever, we clear the npm cache.

We run

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

to force clear the NPM cache with

sudo npm cache clean -f

Then we install the latest version of n with

sudo npm install -g n

We run the latest stablke version with

n stable
Categories
JavaScript Answers

How to protect the password field in Mongoose/MongoDB so it won’t return in a query when populating collections with JavaScript?

To protect the password field in Mongoose/MongoDB so it won’t return in a query when populating collections with JavaScript, we set the select option to false.

For instance, we write

const userSchema = new Schema({
  name: { type: String, required: false, minlength: 5 },
  email: { type: String, required: true, minlength: 5 },
  phone: String,
  password: { type: String, select: false },
});

to create a schema with the password field having the select option set to false.

Then the field’s value won’t be returned when we query the userSchema.