Supertest not sending cookie on POST Route

51 Views Asked by At

I'm working on an Express.js application, and I'm trying to use Supertest for testing my API endpoints. However, I've encountered an issue where Supertest doesn't seem to send cookies with my requests, even though I've set them using set() in my tests.

This is my targeted route :

Router.post("/", AuthenticateRoute, PostController.createPost);

This is my authentication logic :

function AuthenticateRoute(request, response, next) {
  console.log(request.cookies.jwt);

  if (!request.cookies.jwt)
    return next(new AppError("Please login to continue", 401));

  const token = request.cookies.jwt;
  const payload = jwt.verify(token, "rohan");

  request._user = payload;
  next();
}

This is my CreatePost Fn :

exports.createPost = CatchAsync(async (req, res) => {
  req.body.author = req.user._id;
  const { title, body } = req.body;
  const Post = await PostModel.create({ title, body, author });
  res.status(201).json({ Post });
});

Finally and this is my test case :

function mockSignin() {
  const mockUser = {
    id: new mongoose.Types.ObjectId().toHexString(),
    email: "[email protected]",
    userName: "DevRohan",
  };

  const token = jwt.sign(mockUser, "rohan");
  return token;
}

beforeAll(async () => {
  const mongoServer = await MongoMemoryServer.create();
  const dbUrl = mongoServer.getUri();
  await mongoose.connect(dbUrl);
});

beforeEach(async () => {
  const collections = await mongoose.connection.db.collections();

  for (let collection of collections) {
    await collection.deleteMany({});
  }
});

describe("Post", () => {
  it("should create a post when user is logged in", async () => {
    const token = mockSignin();
    const res = await request
      .post("/api/v1/posts")
      .set("Cookie", `token=${token}`)
      .send({
        title: "rohan",
        body: "I am rohan",
      });
    expect(res.status).toBe(201);
    expect(res.body.status).toBe("Success");
  });
});

Also i will be indebted towards your favour , if you could guide how can i add mock middleware to add request._user .

0

There are 0 best solutions below