如何使用jest和aws-sdk-mock在无nodejs无服务器应用程序中模拟或存根aws-sdk的lambda.invoke()方法?

时间:2019-11-19 09:08:00

标签: node.js amazon-web-services aws-sdk serverless aws-sdk-mock

我想在本地自动运行集成测试用例。 这是我要测试的原始文件,即create.js:-

    const jobs=[
    { id: 1,title: 'NodeJS Developer'}, {id: 2, title:'Angular Developer'}
];


var AWS = require('aws-sdk');
AWS.config.region = 'ap-south-1';


let lambda = new AWS.Lambda({
    region: 'ap-south-1',
    //endpoint: 'http://localhost:3000'
})
module.exports.handler=async(evt,ctx)=>{
    console.log("EVENT");
    console.log(evt);
    console.log("EVENT-BODY");
    console.log(evt.body);
    console.log("CTX");
    console.log(ctx);
    console.log("CTX-BODY");
    //console.log(ctx.body);
    var responseData;
    jobs.push(JSON.parse(evt.body));
    var lambda_args={};
    var lambdaOne=()=>{
    return lambda.invoke({
        FunctionName: 'sls-demo-dev-listJobs',
        InvocationType: 'Event',
        Payload:JSON.stringify(lambda_args)    
    }).promise();
}

    responseData=await lambdaOne().then();
    //console.log(response);
    return {
        statusCode :200,
        body:JSON.stringify({
            jobs,responseData
        }),

    }
}

被调用的lambda是一个list.js,它实际上是部署后的sls-demo-dev-listJobs:-

const AWS=require('aws-sdk');


 const jobs=[
        { id: 1,title: 'NodeJS Developer'},
        {id: 2, title:'Angular Developer'}
    ];

    module.exports.handler=async(evt,ctx)=>{
        console.log(evt);
        console.log(evt.body);
        console.log(ctx);
        console.log(ctx.body);
        return {
            statusCode :200,
            body:JSON.stringify({
                jobs
            })
        }
    }

现在我已经尝试过api.integration.test.js的测试文件了:-

describe('Invoking Lambda Offline',()=>{


        console.log('booo!!!');




    test('testing',async()=>{


        const evt={ body: '{\n\t"id":"3",\n\t"title":"vue js"\n}',
        headers:
         { 'Content-Type': 'application/json',
           'cache-control': 'no-cache',
           'Postman-Token': '1cec4e6a-105b-49b5-bce3-27d91121dad6',
           'User-Agent': 'PostmanRuntime/7.4.0',
           Accept: '*/*',
           Host: 'localhost:3000',
           'accept-encoding': 'gzip, deflate',
           'content-length': '32',
           Connection: 'keep-alive' },
        httpMethod: 'POST',
        multiValueHeaders:
         { 'Content-Type': [ 'application/json' ],
           'cache-control': [ 'no-cache' ],
           'Postman-Token': [ '1cec4e6a-105b-49b5-bce3-27d91121dad6' ],
           'User-Agent': [ 'PostmanRuntime/7.4.0' ],
           Accept: [ '*/*' ],
           Host: [ 'localhost:3000' ],
           'accept-encoding': [ 'gzip, deflate' ],
           'content-length': [ '32' ],
           Connection: [ 'keep-alive' ] },
        multiValueQueryStringParameters: null,
        path: '/jobs',
        pathParameters: null,
        queryStringParameters: null,
        requestContext:
         { accountId: 'offlineContext_accountId',
           apiId: 'offlineContext_apiId',
           authorizer:
            { principalId: 'offlineContext_authorizer_principalId',
              claims: undefined },
           httpMethod: 'POST',
           identity:
            { accountId: 'offlineContext_accountId',
              apiKey: 'offlineContext_apiKey',
              caller: 'offlineContext_caller',
              cognitoAuthenticationProvider: 'offlineContext_cognitoAuthenticationProvider',
              cognitoAuthenticationType: 'offlineContext_cognitoAuthenticationType',
              cognitoIdentityId: 'offlineContext_cognitoIdentityId',
              cognitoIdentityPoolId: 'offlineContext_cognitoIdentityPoolId',
              sourceIp: '127.0.0.1',
              user: 'offlineContext_user',
              userAgent: 'PostmanRuntime/7.4.0',
              userArn: 'offlineContext_userArn' },
           protocol: 'HTTP/1.1',
           requestId: 'offlineContext_requestId_ck2znn53p00040seaed2qfyf4',
           requestTimeEpoch: 1573792873610,
           resourceId: 'offlineContext_resourceId',
           resourcePath: '/jobs',
           stage: 'dev' },
        resource: '/jobs',
        stageVariables: null,
        isOffline: true         
        }
        const ctx=null;
        AWSMock.setSDKInstance(AWS); 
        AWSMock.mock('Lambda', 'invoke', function(params, callback){
            console.log('called outer mock')
            if (params.FunctioName === 'sls-demo-dev-listJobs'){
                console.log('called inner if mock')
                callback(null, lambdaOneResponse)
            }
        var lambdaOneResponse={
            'statusCode':'200',
            'invokedResult':'Hi there'
        }
    })
        const response=await createLambdaResponse.handler(evt,ctx);

        console.log(response.statusCode);
        console.log(response.invokedResult);
        const b={};
        expect(response).toEqual(b);
    })
})

我是无服务器和nodejs的新手。请提前帮助

0 个答案:

没有答案