gpt4 book ai didi

node.js - 如果 AWS Lambda 本地调用,如何在 Jest 测试中传递正确的 JSON 事件

转载 作者:太空宇宙 更新时间:2023-11-03 23:15:42 24 4
gpt4 key购买 nike

我有一个 lambda(在 Node.js 中),它可以在生产中使用:

'use strict';

const AWS = require('aws-sdk');
const Politician = require('../model/politician.js');

const dynamoDb = new AWS.DynamoDB.DocumentClient();

module.exports.put = async (event, context) => {

const requestBody = new Politician(JSON.parse(event.body));

return await submit(requestBody)
.then(res => {
return {
statusCode: 200,
body: JSON.stringify({
message: `Successfully submitted politician with name ${requestBody.name}`,
politicianId: res.id
})
}

})
.catch(err => {
return {
statusCode: 500,
body: JSON.stringify({
message: `Error while submitting politician with name ${requestBody.name}`,
})
}
});

};

const submit = politician => {

return new Promise((resolve, reject) => {
if (politician) {
resolve(politician);
} else {
reject(new Error('it all went bad!'));
}
});
};

尝试设置 Lambda 的本地测试时会出现问题(我正在使用 Serverless framework )。问题是我似乎无法提供任何不产生的事件格式:

SyntaxError: Unexpected token u in JSON at position 0

12 | console.log(typeof event.body);
13 |
> 14 | const requestBody = new Politician(JSON.parse(event.body));
| ^
15 |
16 |
17 | return await submit(requestBody)

at JSON.parse (<anonymous>)
at Object.parse [as put] (functions/coxon-put-politician.js:14:45)
at Object.put (functions-test/coxon-put-politician.test.js:37:37)

所以它是未定义的,当我这样做时:

'use strict';
const AWS = require('aws-sdk');
const options = {
region: 'localhost',
endpoint: 'http://localhost:8000'
};
AWS.config.update(options);

const eventStub = require('../events/graham.richardson.json');
const lambda = require('../functions/coxon-put-politician');

describe('Service politicians: mock for successful operations', () => {

test('Replies back with a JSON response', async () => {
const event = '{"body":' + JSON.stringify(eventStub) + '}';
const context = {};

const result = await lambda.put(event, context);

console.log(data);
expect(result).toBeTruthy();
expect(result.statusCode).toBe(200);
expect(result.body).toBe(`{"result":"${result}"}`);
expect(result.body.message.toContain('Successfully submitted politician'))

});
});

或产生:

SyntaxError: Unexpected token o in JSON at position 1

12 | console.log(typeof event.body);
13 |
> 14 | const requestBody = new Politician(JSON.parse(event.body));
| ^
15 |
16 |
17 | return await submit(requestBody)

at JSON.parse (<anonymous>)
at Object.parse [as put] (functions/coxon-put-politician.js:14:45)
at Object.put (functions-test/coxon-put-politician.test.js:38:37)

当我尝试这个时:

'use strict';
const AWS = require('aws-sdk');
const options = {
region: 'localhost',
endpoint: 'http://localhost:8000'
};
AWS.config.update(options);

const eventStub = require('../events/graham.richardson.json');
const lambda = require('../functions/coxon-put-politician');

describe('Service politicians: mock for successful operations', () => {

test('Replies back with a JSON response', async () => {
const event = { body: eventStub };
const context = {};

const result = await lambda.put(event, context);

expect(result).toBeTruthy();
expect(result.statusCode).toBe(200);
expect(result.body).toBe(`{"result":"${result}"}`);
expect(result.body.message.toContain('Successfully submitted politician'))

});
});

所以看来无论我采取哪种方式,我都会收到错误。那么我应该将什么作为事件传递到测试中,以便 JSON.parse(event) 起作用?

最佳答案

TL;DR: const event = { body: JSON.stringify(eventStub) }

您的生产代码可以正常工作,因为代码是针对预期的有效负载结构正确编写的,其中 event 是一个对象,event.body 是一个可解析 JSON 的字符串。

在第一个测试中,您传递的 event 不是作为对象,而是作为可解析 JSON 的字符串。 event.body 未定义,因为 event 作为字符串没有 body 作为参数。

您的测试应该是 const event = { body: JSON.stringify(eventStub) },请注意,它是一个带有 body 属性(字符串)的对象。

在第二次尝试中,您传入一个对象,然后当您尝试 JSON.parse() 该对象时,它会抛出错误。

注意错误:

Unexpected token o in JSON at position 1

oobject... 的位置 1,就像 uundefined 的位置 1。

关于node.js - 如果 AWS Lambda 本地调用,如何在 Jest 测试中传递正确的 JSON 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55787756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com