0
0
Expressframework~10 mins

Middleware testing strategies in Express - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a simple Express middleware function that logs the request method.

Express
function logger(req, res, [1]) {
  console.log(req.method);
  next();
}
Drag options to blanks, or click blank then click option'
Ahandle
Bdone
Ccallback
Dnext
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect parameter names like 'done' or 'callback' instead of 'next'.
Forgetting to call the next function.
2fill in blank
medium

Complete the code to test an Express middleware that adds a property to the request object.

Express
const req = {};
const res = {};
const next = () => {};
middleware(req, res, [1]);
console.log(req.customProperty);
Drag options to blanks, or click blank then click option'
Adone
Bnext
Ccallback
Dhandle
Attempts:
3 left
💡 Hint
Common Mistakes
Passing incorrect function names instead of 'next'.
Not passing a function as the third argument.
3fill in blank
hard

Fix the error in the test code that checks if middleware calls next with an error.

Express
middleware(req, res, (err) => {
  if (err) {
    console.log('Error handled');
  }
  [1];
});
Drag options to blanks, or click blank then click option'
Areturn
Bthrow err
Cnext()
Dconsole.error(err)
Attempts:
3 left
💡 Hint
Common Mistakes
Calling next() inside the error handler callback.
Throwing the error instead of handling it.
4fill in blank
hard

Fill both blanks to create a test that verifies middleware modifies the response and calls next.

Express
const res = {
  statusCode: 200,
  [1]: function(code) {
    this.statusCode = code;
    return this;
  }
};

middleware(req, res, [2]);
Drag options to blanks, or click blank then click option'
Astatus
Bnext
Csend
Ddone
Attempts:
3 left
💡 Hint
Common Mistakes
Using send instead of status for setting status code.
Passing incorrect function names instead of next.
5fill in blank
hard

Fill all three blanks to test middleware that conditionally skips to next middleware.

Express
function testMiddleware(req, res, [1]) {
  if (!req.user) {
    [2]();
    return;
  }
  res.message = 'User found';
  [3]();
}
Drag options to blanks, or click blank then click option'
Anext
Bdone
Dcallback
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the next function parameter and calls.
Not calling next() to continue middleware chain.