带有自定义授权器的无服务器lambda单元测试处理程序



我的无服务器lambda应用程序具有自定义授权程序

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

我正在为用户处理程序编写jest单元测试,但由于在部署时,自定义授权是在执行用户处理程序之前运行的,如何应用相同的内部单元测试,以便在运行用户处理程序测试之前应用授权?

这是我的测试

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);
}
});
});

});

我尝试使用mock jws库,它对我很有用。

在这里,我试图通过嘲笑auth0jsonwebtoken提供的jwks库来单独测试authorizer。如果authorizer测试成功,那么您可以单独测试受保护的端点,或者生成一个jwt令牌,并从我提供的代码中生成一个poilicy,如果返回了允许策略,则测试受保护端点

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);
});

serverless.yml中的authorizer键基本上告诉API网关为特定的API端点使用什么authorizer函数,authorizer仅在通过API部署和调用lambda时使用,不能真正在本地测试此流,即通过单元测试。

你不必和它的授权人一起测试你的函数,以防你的授权人操纵事件,比如提取JWT,你应该模拟测试中的那些过程,并将处理后的事件传递给目标函数。

如果你想测试authoirzer,你应该为它写一个单独的测试

最新更新