首页 > 解决方案 > 使用 serverless-mocha-plugin 测试动态端点

问题描述

我正在使用无服务器框架在 NodeJS 中创建 API 应用程序。我已经安装serverless-mocha-plugin并正在尝试为我的功能创建一些单元测试。

在我的serverless.yml文件中,我有以下端点:

...
equipmentGetAll:
  handler: ./api/equipment/equipment.getAll
  events:
   - http:
     path: equipment
     method: get
     cors: true
equipmentGetOne:
  handler: ./api/equipment/equipment.getOne
  events:
    - http:
      path: equipment/{po_number}
      method: get
      cors: true
...

在测试getAll端点时,我使用了以下成功通过的测试。我已经通过将响应记录到控制台来验证它是否有效。

'use strict';

// tests for equipmentGetAll
// Generated by serverless-mocha-plugin

const mochaPlugin = require('serverless-mocha-plugin');
const expect = mochaPlugin.chai.expect;
let wrapped = mochaPlugin.getWrapper('equipmentGetAll', '/api/equipment/equipment.js', 'getAll');

describe('equipmentGetAll', () => {
  before((done) => {
    done();
  });

  it('should get all Equipment', () => {
    return wrapped.run({po_number:117}).then((response) => {
      expect(response.statusCode).to.be.equal(200);
      expect(response.body.length).to.be.greaterThan(0);
    });
  });
});

同样,对于getOne端点,我(现在)正在做一个非常相似的测试:

'use strict';

// tests for equipmentGetOne
// Generated by serverless-mocha-plugin

const mochaPlugin = require('serverless-mocha-plugin');
const expect = mochaPlugin.chai.expect;
let wrapped = mochaPlugin.getWrapper('equipmentGetOne', '/api/equipment/equipment.js', 'getOne');

describe('equipmentGetOne', () => {
  before((done) => {
    done();
  });

  it('should get one single Equipment', () => {
    return wrapped.run({}).then((response) => {
      expect(response.statusCode).to.be.equal(200);
      expect(response.body.length).to.be.equal(1);
    });
  });
});

问题

我收到的当前回复getOne是:

{ 
  statusCode: 500,
  headers: { 'Content-Type': 'text/plain' },
  body: 'Cannot read property \'po_number\' of undefined' 
}

由于from的路径不仅仅是. _getOneserverless.ymlequipment/{po_number}equipment/

传递测试路径值的正确方法是什么?

示例调用将命中端点my-api-endpoint.com/equipment/117并返回带有po_number 117. 这在使用 POSTMan 进行测试时可以正常工作,但是我怎样才能使它与 POSTMan 一起工作mocha-serverless-plugin呢?

标签: node.jsunit-testingmocha.jsserverlessaws-serverless

解决方案


要将数据传递给 lambda,您应该使用
wrappedLambda.run({body: "String, not Object"})

要将 queryStringParametr 传递给 lambda,您应该使用 wrappedLambda.run({queryStringParameters: {a: "first",b:"second"}})

要将 pathParameters 传递给 lambda,您应该使用 wrappedLambda.run({pathParameters: {a: "first", b:"second"})

测试post方法的简单示例

 context('save flashcard', () => {
        before((done) => {
            done();
        });
        it('save flashcard successfully', () => {
            return saveFlashcard.run({body: correctInput})
                .then((response) => {
                    const body = JSON.parse(response.body);
                    expect(body).to.have.property('_id')
                })
        });
});

该主体将位于事件对象内。


推荐阅读