【问题标题】:Jest testing Lambdas with no proper functions? Node.js开玩笑地测试没有适当功能的 Lambda?节点.js
【发布时间】:2018-08-30 09:27:43
【问题描述】:

使用 AWS Lambda 来简单地发布信息,已经为我的代码分支编写(并且正在通过)测试。但是,我不知道如何测试 return 语句是否被调用...

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

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 });
  });
};

--- 测试 --- 我已经设法测试了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();
    });
  });

但是我希望测试这条线: return virtualService.publish(event, headers[filenameHeader], callback);...

我写了一些我知道是错误的东西,但我希望它有点朝着正确的方向......

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

【问题讨论】:

    标签: javascript node.js aws-lambda jestjs


    【解决方案1】:

    我没有测试它,但我认为用 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();
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-25
      • 2020-10-08
      • 2017-11-28
      • 1970-01-01
      • 2020-12-15
      • 2020-07-04
      • 1970-01-01
      • 2017-10-17
      • 2021-12-31
      相关资源
      最近更新 更多