I have, what I thought was, a simple "plain-vanilla-ish" 4-file toy solution. I want to write a Jest test for the bingo.js authenticated route '/'. Here are the four files that show the complete set-up.
index.js, the Express app rootroutes/auth.js, a simple authenticationPOSTendpoint that checks the userroutes/bingo.js, an endpoint that requires the user to be authenticated, andmiddleware/authentication.js, a simple middleware that checks the session user
I'm banging my head against the wall, trying to figure out how to write unit tests for the bingo.js endpoint, without having to run the entire app through index.js - I don't need full end-to-end tests here, that's what the Cypress tests are for.
I've tried to find ways to call just the auth step, I've tried mocking sessions, I've tried to figure out how to set the session on Supertest...
Please can someone at least point me in the right direction?
index.js
// index.js
const express = require("express");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const app = express();
const bingoRouter = require("./routes/bingo");
const authRouter = require("./routes/auth");
// middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(
session({
cookie: { maxAge: 300000 },
store: new session.MemoryStore(),
saveUninitialized: true,
resave: "true",
secret: "our_really_secret_key",
})
);
app.use("/bingo", bingoRouter);
app.use("/auth", authRouter);
app.use((req, res) => {
return res.status(404).json({
error: "Not Found",
});
});
app.listen(port);
module.exports = app;
auth.js
// routes/auth.js
const express = require("express");
const router = express.Router();
const jwt = require("jsonwebtoken");
const secretKey = "our_really_secret_key";
// Authenticate user
router.post("/login", async (req, res) => {
const { username, password } = req.body;
const user = { username: "username", password: "password", is_admin: true };
if (user && user.password === "password") {
req.session.user = user;
res.redirect("/bingo");
} else {
res.render("auth", { error: "Invalid username or password" });
}
});
bingo.js
// routes/bingo
const { isAdmin } = require("../middleware/authentication");
const express = require("express");
const router = express.Router();
router.use(isAdmin);
router.get("/", async function (req, res) {
res.render("bingo", {
user: req.session.user,
});
});
module.exports = router;
authentication.js
// middleware/authentication.js
exports.isAdmin = (req, res, next) => {
if (req.session.user && req.session.user.is_admin) {
// User is authenticated & admin, allow access to route
next();
} else {
// User is not authenticated or not admin, redirect to login page
res.redirect("/auth");
}
};
from How do I write a Jest test for an authenticated Express endpoint?
No comments:
Post a Comment