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";
[...]
    expect.assertions(2);
    // 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);
    expect(ctx.session.user).toBeTruthy();
    // ...and log em out
    await resolvers.Mutation.logout(null, null, ctx);
    expect(ctx.session).toBeFalsy();
[...]
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!
 

 
    
Top comments (0)