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

时间:2019-04-21 23:55:23

标签: node.js aws-lambda jestjs serverless-framework

我有一个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)起作用?

1 个答案:

答案 0 :(得分:2)

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()传递对象时出错。

请注意该错误:

  

JSON中位置1处的意外令牌o

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