DEV Community


Testing Logout Resolver (GraphQL & express-session)

tmns profile image tmns ・1 min read

Hey all, last week I was putting together a GraphQL API and while implementing authentication found myself stuck trying to test my logout resolver. The issue was that the logout resolver calls session.destroy() (implemented by express-session) but since it was calling the resolver directly, I was unsure of how to actually pass a real Session object (with the required properties / methods, such as destroy) to the resolver, as this is normally handled by the middleware.

Eventually, by looking at the source code for express-session, I was able to figure out how to create a valid Session object. In the end, my test looked like:

import { MemoryStore, Cookie } from "express-session";
    // create user to first authenticate and obtain valid session with
    await User.create({ username: "name", password: "password" });
    var args = {
      input: {
        username: "name",
        password: "password"

    // mock session object building
    var ctx = {
      sessionStore: new MemoryStore()

    var cookie = new Cookie();

    // adds valid session object to ctx
    ctx.sessionStore.createSession(ctx, { cookie });

    // log our test user in...
    await resolvers.Mutation.login(null, args, ctx);

    // ...and log em out
    await resolvers.Mutation.logout(null, null, ctx);
Enter fullscreen mode Exit fullscreen mode

However, this is my first time building and testing something like this on my own - so I wanted to know if there's a known / better way of handling this issue. I searched quite a bit but the examples I found pertained to other session packages like cookie-session, using GraphQL on top of a REST API, and other close, but not quite issues / solutions.

Any insight would be appreciated!

Discussion (0)

Forem Open with the Forem app