How to mock/generate cognito jwt token in unit tests?

Viewed 941

What's the best approach around mocking/generation a Cognito token in tests?

I have a helper function that sets the Authorization header:

const response = await request(service)
    .post('/graphql')
    .send({ query, variables })
    .set('Authorization', `Bearer ${token}`)

It seems like I need to generate the token myself but I'm not sure how to or if I even can do so.

1 Answers

You can use Auth.signIn function to programmatically login and receive jwt token from Cognito. Some thing like

import { Auth } from 'aws-amplify'

const signIn = Auth.signIn({ username, password })
signIn.then(cognitoResponse => {
  // this is the token you need
  console.log(cognitoResponse.signInUserSession.accessToken.jwtToken);
})

Auth.signIn document:

https://aws-amplify.github.io/amplify-js/api/classes/authclass.html#signin

Related