How to mock OAuth flow? #1368
-
Hey, I understand that MSW is mostly used to mock API endpoints. But I was wondering if it can be used to mock something like when authenticating with slack (https://slack.com/oauth/v2/):
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hey, @cmacdonnacha. Yeah, sure. Authentication also involves API requests to endpoints, so no extra case here. I haven't worked with the Slack API per se but I imagine it's not much different from other OAuth protocols. Here's how I'd mock a GitHub OAuth: rest.get('https://github.com/oauth/v2/authorize', (req, res, ctx) => {
const callbackUrl = new URL('http://localhost:3000/oauth/callback')
callbackUrl.searchParams.set('code', 'abc-123')
// Redirect to the local OAuth callback route with a mock "code".
// The route handler for this callback remains as-is, no need to mock it.
return res(ctx.status(301), ctx.set('Location', callbackUrl))
})
rest.post('https://github.com/oauth/v2/authorize', async (req, res, ctx) => {
const { code } = await req.json()
// Mock a successful authorization payload.
return res(ctx.json({
access_token: mockAccessToken()
})
}) Just keep in mind that MSW intercepts fetch requests. So you cannot intercept a navigation request if your app opens For in-browser flows skip the entire thing and only mock the authorization endpoint of your service (i.e. |
Beta Was this translation helpful? Give feedback.
-
Leaving my findings here in case people stumble across this in the future: If your use case is integration testing with Playwright, then you can use Playwrights functionality to mock out redirects to external pages like this: await page.route("https://github.com/oauth"), async (route) => {
await route.fulfill({
status: 302,
headers: {
Location: "https://yourdomain.com/oauth",
},
});
}); If you have to make it work with msw, the only other option I found is to change the redirect URI of the OAuth flow button depending on an environment variable. You might already have an environment variable to determine if msw should be loaded when starting the server, so you could use the same one to change out github.com/oauth to yourdomain.com/oauth, like shown in this video. |
Beta Was this translation helpful? Give feedback.
Hey, @cmacdonnacha.
Yeah, sure. Authentication also involves API requests to endpoints, so no extra case here. I haven't worked with the Slack API per se but I imagine it's not much different from other OAuth protocols.
Here's how I'd mock a GitHub OAuth: