使用Lambda的测试功能进行测试时获得响应“ Null”

时间:2019-06-21 17:58:09

标签: node.js amazon-web-services testing aws-lambda amazon-connect

我正在调用Lambda函数,该函数通过Lambda中的API调用从ServiceNow检索数据。我已经将调用流与Amazon Connect一起使用了代码进行了测试,但是当尝试使用Lambda测试功能时,它会成功,但是返回的响应为null,并且至少要返回一个名称。

从Amazon Connect到Lambda函数的输入是一个电话号码,我尝试将其添加到参数部分和customerEndpointAddress部分。

Sub

我使用的测试代码是:

const https = require('https');

//Get Phone Details of Customer via Typed in Phone Number or Actual Phone Number
const getPhone = contact => {
    const phone = contact.Details.ContactData.CustomerEndpoint.Address;
    console.log(`Customer Phone is : ${phone}`);
    return phone.length === 13 ? `0${phone.substring(3)}` : phone;
}

//Set API config, passing in the Phone Parameter as query and return both firstname and SysId
const getPhoneRequestOptions = phone => {
    const path = `/api/now/table/sys_user?sysparm_query=phone%3D${phone}^ORmobile_phone%3D${phone}&sysparm_fields=first_name,sys_id`;
    return {
        host: process.env.SERVICENOW_HOST,
        port: '443',
        path: path,
        method: 'get',
        headers: {
            "Content-Type": 'application/json',
            Accept: 'application/json',
            Authorization: 'Basic ' + Buffer.from(`${process.env.SERVICENOW_USERNAME}:${process.env.SERVICENOW_PASSWORD}`).toString('base64'),
        }
    };
};

//Retrieve data, in this case firstname and SysId
const requestUser = (phone, callback) => {
    let get_request = https.request(getPhoneRequestOptions(phone), res => {
        let body = '';
        res.on('data', chunk => {body += chunk});
        res.on('end', () => {callback(JSON.parse(body))});
        res.on('error', e => {callback(e.message)});
    })
    get_request.end();
}

//Return data
exports.handler = (contact, context, callback) => {
    if (!contact.Details || !contact.Details.Parameters) return;
    requestUser(getPhone(contact), response => {
        if (response.result && response.result[0] && response.result[0].first_name) {
            callback(null, {
                "first_name": response.result[0].first_name
            });
        } else {
            callback(null, {
                "Error": "No user found"
            });
        }
    });
};

调用代码后,将在Amazon Connect中返回名称“ Abel”,但对它运行测试用例并非如此。

1 个答案:

答案 0 :(得分:0)

是因为这一行:

if (!contact.Details || !contact.Details.Parameters) return;

在测试事件中,您使用的Details不具有属性Parameters(仅ContactData)。这会导致您返回时没有返回值。