如何在 AWS Lambda 本地调用的 Jest 测试中通过正确的 JSON 事件

Howto pass correct JSON Event in Jest test of AWS Lambda local invocation

我有一个 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。