Using serverless-mocha-plugin to test dynamic endp

2019-07-06 22:05发布

I am creating an API application in NodeJS using the Serverless framework. I have installed the serverless-mocha-plugin and am trying to create some unit tests for my functions.

In my serverless.yml file, I have the following endpoints:

...
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
...

When testing the getAll endpoint, I use the following test which passes successfully. I have verified it works by logging the response to the console.

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

Similarly, for the getOneendpoint, I am (for now) doing a very similar test:

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

The Problem

The current response I'm receiving for getOne is:

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

Due to the fact that the path for getOne from serverless.yml is equipment/{po_number} rather than just equipment/.

What is the proper way to pass the path value for the test?

A sample call would hit endpoint my-api-endpoint.com/equipment/117 and return the Equipment with po_number 117. This works properly when testing with POSTMan, but how can I make it work with mocha-serverless-plugin?

0条回答
登录 后发表回答