-
Notifications
You must be signed in to change notification settings - Fork 21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to test middleware? #18
Comments
I am having a very similar issue, but in my case I am trying to mock the isAuth and call next() as a mock implementation, but I don't think it's being made available in the test. https://stackoverflow.com/questions/67768435/proper-way-to-test-type-graphql-middleware-with-jest. |
@riggedCoinflip have you tried mocking the import? https://stackoverflow.com/questions/60722281/testing-an-express-middleware-with-jest? jest.mock("pathToYourAuthModule", () => {
return {
isAuth: jest.fn((req,res,next) => next()), //and/or you can set your req.user.isAuth to true
};
}); if your authentication module has other functionality you want to keep unmocked, see https://jestjs.io/docs/jest-object#jestrequireactualmodulename |
I'm having the same issue. |
@nogashimoni @riggedCoinflip howdy folks! It looks like this is a bug with the way this library simulates the graphql requests. I have a failing test that reproduces the issue, so I'll be looking into possible solutions this week. |
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. @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. |
I am searching for a way to test my authorization middleware.
I use express middleware to validate my authorization token.
I then apply the middleware
Lastly, I wrap my
graphql-compose
resolvers that require authentication with this function:In the end I got it working like this:
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.The text was updated successfully, but these errors were encountered: