Serverless lambda unit test handlers with custom authorizer

Viewed 487

My serverless lambda application has custom authorizer

  verify-token:
    handler: app/Middleware/VerifyToken.auth

  user:
    handler: app/Handlers/Users.user
    events:
      - http:
          path: user
          method: get
          cors: true
          authorizer: verify-token

I am writing jest unit test for the user handler, but since when deployed the custom authorization is run before the user handler is executed, How do I apply the same in jest unit test so that I can apply the authorization before running the user handler test?

This is my test

const  { user }  = require('../../app/Handlers/Users');

/**
 * Tests for get()
 */
describe('Get user', () => {

    it('Get user data', async done => {
        let userEvent = {
            headers: {
                'authorization': 'Bearer TOKEN'
            }
        }
        // user.authorizer();
        user(userEvent, null, (error, data) => {
            try {
                expect(data.statusCode).toBe(200);
                done();
            } catch (error) {
                done(error);
            }

        });
    });


});
2 Answers

I tried using mock-jws library and it works for me.

here i am trying to test authorizer seperately by mocking jwks library provided by auth0 jsonwebtoken. If authorizer test is succesful then either you can separately test your protected endpoint or generate a jwt token, and generate a poilicy from the code i provided and if allow policy is returned test your protected endpoint

const createJWKSMock = require('mock-jwks');
const authorizer = require('../authorizer/authorizer');

describe('Auth Test', () => {
  const jwks = createJWKSMock.default('https://your domain here');

  beforeEach(() => {
    jwks.start();
  });

  afterEach(() => {
    jwks.stop();
  });
  test('should verify the token', async () => {
    const token = jwks.token({
      aud: 'https://your audience,
      iss: 'https://issuer of token',
    });
    console.log(token);
    const event = {
      authorizationToken: `Bearer ${token}`,
    };
    const policy = await authorizer.auth(event, 'context');
    console.log('jatin', policy);
    expect(policy.context).not.toBe(undefined);
  });

The authorizer key in serverless.yml basically tell API Gateway what authorizer function to use for a particular API endpoint, the authorizer is only used when you have deployed and invoke the lambda via API, you can't really test this flow locally, i.e. by unit test.

You don't have to test your function along with its authorizer, in case your authorizer will manipulate the event, like extract the JWTm, you should mock those processes in your test and pass the processed event to the targeting function.

If you want to test authoirzer, you should write a separate test for it.

Related