javascript - 在没有适当功能的情况下开 Jest 测试 Lambda? Node.js

标签 javascript node.js aws-lambda jestjs

使用 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();
    })
  })

最佳答案

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

关于javascript - 在没有适当功能的情况下开 Jest 测试 Lambda? Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49403305/

相关文章:

amazon-web-services - 从 cloudwatch 日志组到 lambda 的 aws 传入数据已损坏

aws-lambda - 在 API Gateway 端点后面本地测试 AWS Lambda

javascript - 使用隐藏和显示时使浏览器的后退按钮起作用(jquery)

javascript - Laravel 分页表 - 对一列进行排序

node.js - node.js 中的 block 数据记录

node.js - 如果套接字io房间为空,是否会自动销毁?

javascript - 使用触控板时捕获滚轮/鼠标滚轮事件的边缘替代解决方案

javascript - jQuery 可以操作不在 DOM 上的 HTML 吗?

javascript - 通过 iosocket 向 Meteor 发送数据,但不是从 Meteor 客户端(搭载 Meteor 的 io-socket)

Python aws-lambda 返回 xml 文件到 aws-api-gateway