I'm just starting with Jest and I'm trying to test a POST/register
endpoint. This endpoint sends back 2 cookies: accessToken:*jwt*
and refreshToken:*jwt*
.
This is my test file:
import server from "../server"
import supertest from "supertest"
import mongoose from "mongoose"
import dotenv from "dotenv"
dotenv.config()
const request = supertest(server)
describe("Testing Auth endpoints", () => {
beforeAll(done => {
const PORT = process.env.PORT
mongoose
.connect(process.env.MONGO_STRING_TEST!)
.then(() => {
console.log("Connect to Atlas. Test DB.")
done()
})
.catch(err => console.log(err))
})
const validUser = {
name: "Paul Stevens",
email: "ps@g.com",
password: "1234",
role: "host",
}
it("should test /register for a valid request and return 201 status code and accessToken and refreshToken through cookies", async () => {
const resp = await request.post("/users/register").send(validUser)
// I want the content of the cookies here
})
afterAll(done => {
mongoose.connection.close(() => {
done()
})
})
})
This is the endpoint. I'm testing this stuff so I'm actually sending the tokens both in the response body and the cookies.
UsersRouter.post("/register", async (req, res, next) => {
try {
const newUser = new UserModel(req.body)
const savedUser = await newUser.save()
const { accessToken, refreshToken } = await getTokens(savedUser)
res.cookie("accessToken", accessToken, { httpOnly: true })
res.cookie("refreshToken", refreshToken, { httpOnly: true })
res.status(201).send({ accessToken, refreshToken, user: savedUser })
} catch (error) {
next(createError(400, error as Error))
}
})
How can I retrieve both tokens so I can reuse them to test other endpoints? I was able to see that the cookies are there under resp.header["set-cookie"] but this is an array with two strings containing the tokens. Is there a better way to simply extract the tokens?