With Supertest, how do you test a login-protected Express route, and why can a shared request.agent make an anonymous-access test pass or fail depending on test order?
answer
- stateless calls versus a jar
- redirects are not followed
- the login answers 302
- one agent per test
basics
~20 sSupertest's request(app) keeps no cookies between calls, while request.agent(app) stores each Set-Cookie and sends it on later requests. An agent shared across tests carries one test's login into the next, so an anonymous-access check depends on order.
solid answer
~40 sEach `request(app)` call is independent, so a cookie set by `POST /login` is gone on the next call. `request.agent(app)` keeps a cookie jar: it saves cookies from responses and redirects and attaches them to later requests from the same agent. So the protected-route test signs in with `agent.post('/login')`, then calls `agent.get('/account')`. Supertest does not follow redirects by default, so when the login answers with `res.redirect()` you assert `.expect(302)` and the `Location` header rather than the account page. The order bug comes from creating one agent at module scope: after the login test runs, a later "anonymous gets 401" test using that agent is signed in. Create a fresh agent per test, and send anonymous cases through plain `request(app)`.
code
javascript · 22 linesconst express = require('express');
const app = express();
app.use(express.json());
app.post('/login', (req, res) => {
if (req.body?.password !== 'correct-horse') {
return res.status(401).json({ error: 'invalid_credentials' });
}
res.cookie('sid', 'session-123', { httpOnly: true });
res.redirect('/account'); // 302 by default
});
app.get('/account', (req, res) => {
const cookies = (req.get('Cookie') ?? '').split('; ');
if (!cookies.includes('sid=session-123')) {
return res.status(401).json({ error: 'sign_in_required' });
}
res.json({ user: 'ada' });
});
module.exports = app;go deeper
Remember that request.agent keeps cookies across requests and request(app) does not.
Explain the login flow: a 302 that Supertest does not follow, the cookie the agent saves, and the follow-up agent request.
Diagnose an anonymous-access test that fails only after the login test, trace it to a shared agent, and restructure so every test owns its jar.
Set the suite convention that tests never share agents or ordering assumptions, so the suite can be shuffled or parallelised safely.
## Two ways to send requests **Supertest** offers two entry points, and the difference between them is state: - **`request(app)`** returns a fresh request factory. Requests made through it carry only what you set on them; a `Set-Cookie` header in one response is not sent with the next request. - **`request.agent(app)`** returns a **test agent** that holds a **cookie jar**. It saves cookies from every response, and from redirects it follows, and attaches the matching ones to every later request it makes. It is the test equivalent of one browser profile staying signed in. A login-protected Express route needs the second: the login response sets a session cookie, and the protected request has to send it back. ## Testing the sign-in flow 1. Create an agent: `const agent = request.agent(app)`. 2. Sign in: `agent.post('/login').send({ password: 'correct-horse' })`. `.send()` with an object sends a JSON body, so the app needs `express.json()` mounted before the login route. 3. Assert the login response. In Express, `res.redirect('/account')` answers **302** by default with a `Location` header, and a Supertest request **does not follow redirects** unless you call `.redirects(n)`. So expect `302` and `Location: /account`, not a 200 page. 4. Call the protected route with the same agent: `agent.get('/account').expect(200)`. The jar supplies the cookie. 5. Test the refusals separately: no cookie, a wrong password, and a cookie that is present but invalid, which you can send explicitly with `.set('Cookie', 'sid=forged')`. ## Why following the redirect is not enough It is tempting to call `.redirects(1)` on a plain `request(app)` login and check that the account page comes back. That does not prove the cookie works: without an agent, the followed request does not carry the cookie set on the 302, so the protected route answers 401. An agent, by contrast, saves the cookie from the redirect response and attaches it to the follow-up. Asserting the 302 and then making an explicit agent request keeps each step visible. ## The order-dependent failure A common shortcut is to create the agent once, at module scope, and reuse it: | Test, in file order | Agent state before it | Result | |---|---|---| | "signs in" with the shared agent | empty jar | 302, cookie saved | | "anonymous gets 401" with the shared agent | holds `sid` | 200: the test fails | Reverse the two tests and both pass. Run only the second and it passes. Nothing in either test is wrong on its own; the defect is the shared object, which is why it tends to surface only when someone adds a test, reorders a file or runs a single case while debugging. That is an **order-dependent test**: its result depends on what ran before it in the same process, because the agent's jar is shared mutable state. The opposite failure exists too: a "can view account" test that passes only because an earlier test happened to sign in, and fails when run alone. ## Keeping tests independent - **Create an agent per test**, inside the test or in a per-test setup hook, so every test starts with an empty jar. - **Use plain `request(app)` for anonymous cases.** It never carries cookies, so it cannot inherit a login. - **Sign in through a helper** that takes a fresh agent, performs the login and returns it, so each test states its own starting point. - **Assert the cookie itself when it matters**: `.expect('set-cookie', /HttpOnly/)` checks an attribute on the login response. - **Keep server-side state in mind.** A fresh agent starts with an empty jar on the client side only; state the app keeps on the server, such as sessions or records a test created, survives between tests in the same process and needs its own reset. ## What the agent does not do The agent is a cookie jar plus defaults, not an authentication helper. It does not understand sessions, tokens or the app's sign-in scheme. For a route protected by a bearer token rather than a cookie, set the header on each request with `.set('Authorization', ...)` or `.bearer(token)`, or call `agent.set()` once so the agent applies that header to every request it makes; the jar plays no part.
- Why does a Supertest login test that expects 200 fail when the Express route ends with res.redirect()?Express's `res.redirect()` answers 302 by default, and Supertest requests do not follow redirects unless `.redirects(n)` is called. The test sees the 302 and its `Location` header, so it should expect exactly that.
- How do you test that a protected Express route rejects a forged session cookie?Use plain `request(app)` and set the cookie yourself, for example `.set('Cookie', 'sid=forged')`, then expect the refusal status. A plain request carries only what you set, so the result does not depend on any earlier login.
- Does creating a new request.agent per test also reset the app's server-side sessions?No. A new agent only starts with an empty cookie jar on the client side. Sessions or other state the app keeps in memory survive across tests in the same process, so a test that relies on clean server state has to reset it itself.
request(app) is a browser with cookies switched off, even across a redirect; request.agent(app) is one browser profile that stays signed in until you throw it away and open a new one.
- request(app) remembers cookies between calls in the same test file.
- Supertest follows the login redirect automatically, so expect 200.
- A single module-level agent is the clean way to share a login.
- Following the redirect with .redirects(1) proves the session cookie works.
- A new agent per test also wipes the app's session store.