我正在使用无服务器框架在 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'
}
由于 serverless.yml
中 getOne
的路径 是 equipment/{po_number}
而不仅仅是 equipment/
。
为测试传递路径值的正确方法是什么?
示例调用将命中端点 my-api-endpoint.com/equipment/117
并返回带有 po_number
117
的设备。这在使用 POSTMan 进行测试时可以正常工作,但是我怎样才能让它与 mocha-serverless-plugin
一起工作?
最佳答案
要将数据传递给 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')
})
});
});
这个主体将位于事件对象内。
关于node.js - 使用 serverless-mocha-plugin 测试动态端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54813784/