简体   繁体   English

开玩笑地测试没有适当功能的Lambda? Node.js的

[英]Jest testing Lambdas with no proper functions? Node.js

Working with AWS Lambda to simply publish information, tests have been written(and are passing) for the branches of my code. 使用AWS Lambda可以简单地发布信息,已经为我的代码分支编写了(并且正在通过)测试。 However, I am unaware of how to test whether the return statement is called or not... 但是,我不知道如何测试return语句是否被调用...

index.js index.js

exports.handler = (event, context, callback) => {
  const headers = event.headers;

  if (! (headers && headers[filenameHeader])) {
    return callback(...);
  }

  if (!(event.body && event.body.length > 0)) {
    return callback(...);
  }

  return virtualService.publish(event, headers[filenameHeader], callback);
};

publish.service.js publish.service.js

exports.publish = (event, filename, callback) => {

  ...

  request(options).then(res => {
    console.log('Success response statusCode:' + res.statusCode);
    return callback(null, { "statusCode": 202 });
  }).catch(err => {
    console.log('Error thrown:' + err);
    return callback(null, { "statusCode": 500, "body": err });
  });
};

--- Tests --- I have managed to test the conditionals of the index.js file with things such as: ---测试---我设法用以下内容测试index.js文件的条件:

test('should return a 400 due to the X-File-Name header not being present', function (done) {
    lambda.handler(event, null, (err, request) => {
      should.not.exist(err);
      should.exist(request);
      expect(request.statusCode).toBe(400);
      expect(console.log).toHaveBeenCalledWith('X-File-Name Header not supplied');
      done();
    });
  });

However I am looking to test the line: return virtualService.publish(event, headers[filenameHeader], callback); 但是,我正在测试以下行: return virtualService.publish(event, headers[filenameHeader], callback); ... ...

I have written something I know to be wrong, but I am hoping that it is somewhat in the right direction... 我写的东西我知道是错的,但我希望它的方向是正确的...

test('test the return function is called within index.js', function(done) {
    lambda.handler(event, null, (err, request) => {
      expect(publish).toHaveBeenCalled();
    })
  })

I did not test it, but I think stubbing virtualService.publish with sinon would work : 我没有对其进行测试,但是我认为使用sinon对virtualService.publish进行存根是可行的:

//import * is important here as it will allow you (and sinon) to get the method reference and stub it
import * as virtualService from './lib/service/publish.service'; 

test('test the return function is called within index.js', () => {
    const stubbedPublish = sinon.stub(virtualService, 'publish');
    //the callback  won't be called as we stubbed virtualService.publish, so I guess we can pass null
    lambda.handler(event, null, null)
    expect(stubbedPublish.callCount).toBe(1);
    virtualService.publish.restore();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM