question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to test middleware?

See original GitHub issue

I am searching for a way to test my authorization middleware.

I use express middleware to validate my authorization token.

//isAuth
//simplified
module.exports = (req, res, next) => {
    const token = req.headers['x-auth-token'];
    if (token invalid) {
        req.user = {
            isAuth: false,
        }
    else {
        req.user = {
            isAuth: true,
            _id: decodedToken._id,
            name: decodedToken.username,
            role: decodedToken.role,
    }
    next();
}

I then apply the middleware

const app = express();
app.use(isAuth);

function createApollo() {
    const apollo = new ApolloServer({
        schema: graphqlSchema,
        context: ({req, res}) => ({req, res}),
    });
    apollo.applyMiddleware({app, path: "/graphql"});
    return apollo
}

Lastly, I wrap my graphql-compose resolvers that require authentication with this function:

module.exports = (resolvers) => {
    Object.keys(resolvers).forEach((k) => {
        resolvers[k] = resolvers[k].wrapResolve(next => async rp => {
            if (!rp.context.req.user.isAuth) {
                throw new Error('You must login to view this.');
            }
            return next(rp)
        })
    })
    return resolvers
}

In the end I got it working like this:

setOptions({
    request: {
        user: {
            isAuth: true,
            _id: decodedToken._id,
            name: decodedToken.username,
            role: decodedToken.role,
        }
    },
});

but that bypasses my isAuth middleware.

Is there any way, using this or any other package to test middleware as well? We could add apollo-client or alike as a dev-dependency and test the queries as if there were directly from frontend, but there has to be a better way.

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:1
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
nogashimonicommented, Jun 8, 2021

I’m having the same issue. Why aren’t express middlewares applied? Is this by design or is it a bug?

0reactions
vitorbalcommented, Jun 15, 2021

So I’ve been taking another look at this and I don’t think it will be possible to solve it without a couple of breaking changes to the API. Specifically, we’d have to make it so this library starts the graphql server and then sends actual http requests to it. Today, we use some of the ApolloServer APIs to simulate a graphql request instead.

@nogashimoni @riggedCoinflip one alternative would be to refactor your middlewares so they can run from within the context callback, like this:

const apolloServer = new ApolloServer({
  schema,
  context: ({ req }) => {
    return isAuth(req);
  },
});

If that’s not okay, then I would recommend looking into a library like supertest that help you test an http server.

Meanwhile, I’m going to do some thinking on what the future of this library is. ApolloServer now exposes an executeOperation API that should make it easier to solve what this library initially set out to solve, but also wouldn’t support testing express middlewares. Perhaps we can rework this library to provide sugar on top of executeOperation, and additionally provide an API to help test apollo-server-express end-to-end too.

Read more comments on GitHub >

github_iconTop Results From Across the Web

An Approach to Testing Middleware | by TJ Miller - Medium
I've always tested middleware in one of two ways, a unit test with mocks and asserting the callback in the handle method or...
Read more >
Testing Middleware in Laravel with PHPUnit - Semaphore CI
In this tutorial, we will show you how to test middleware in Laravel applications. If you are not familiar with the concept of...
Read more >
Unit test Express middleware - TypeScript, Jest
How to Unit Test Express Middleware · Test the business logic, and nothing else · Mock or stub only the needed parts coming...
Read more >
How to Unit Test ASP .NET Core Middleware
In this article, let's have a look at how to test the middleware components / classes using unit tests. Prerequisites You just need...
Read more >
Middleware Testing & SOA - Prolifics Testing
Middleware Testing & SOA ... Testing the crucial connections between your systems to check they're providing the right data to the right processes...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found