Skip to content

Commit

Permalink
AUT-2772: Add currentUrlMiddleware
Browse files Browse the repository at this point in the history
The new language toggle middleware requires a currentUrl property
to be added to res.locals. This commit introduces the property along
with associated tests to verify that it is being set as expected.
  • Loading branch information
gtvj committed May 10, 2024
1 parent 31a016b commit 817b688
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/middleware/current-url-middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { NextFunction, Request, Response } from "express";

export function setCurrentUrlMiddleware(
req: Request,
res: Response,
next: NextFunction,
): void {

res.locals.currentUrl = new URL(
req.protocol + "://" + req.get("host") + req.originalUrl)

next();
}
49 changes: 49 additions & 0 deletions test/unit/middleware/current-url-middleware.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { expect } from "chai";
import { describe } from "mocha";
import { NextFunction, Request, Response } from "express";
import { sinon } from "../../utils/test-utils";
import { setCurrentUrlMiddleware } from "../../../src/middleware/current-url-middleware";
import { mockRequest, mockResponse } from "mock-req-res";

describe("currentUrl middleware", () => {
let req: Partial<Request>;
let res: Partial<Response>;
let next: NextFunction;

const originalUrl = '/sign-in-or-create?lng=cy';
const host = 'signin.account.gov.uk'

beforeEach(() => {
req = mockRequest({
originalUrl,
get: sinon.stub().withArgs('host').returns(host)
});
res = mockResponse();
next = sinon.fake() as unknown as NextFunction;
});

afterEach(() => {
sinon.restore();
});

describe("setCurrentUrlMiddleware", () => {
it("should add currentUrl to request locals", () => {
setCurrentUrlMiddleware(req as Request, res as Response, next);

expect(res.locals).to.have.property("currentUrl");
});

it("currentUrl should contain the scheme, host and originalUrl", () => {
setCurrentUrlMiddleware(req as Request, res as Response, next);
const currentUrlAsString = String(res.locals.currentUrl)

expect(currentUrlAsString).to.eq(`https://${host}${originalUrl}`);
});

it("should call next function", () => {
setCurrentUrlMiddleware(req as Request, res as Response, next);

expect(next).to.have.been.called;
});
});
});

0 comments on commit 817b688

Please sign in to comment.