node.js - 使用 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的路径不仅仅是. _getOne
serverless.yml
equipment/{po_number}
equipment/
传递测试路径值的正确方法是什么?
示例调用将命中端点my-api-endpoint.com/equipment/117
并返回带有po_number
117
. 这在使用 POSTMan 进行测试时可以正常工作,但是我怎样才能使它与 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')
})
});
});
该主体将位于事件对象内。
推荐阅读
- audio - 在 python 中使用 ffmpeg 从视频幻灯片 (mp4) 和音频 (wav) 中导出 ogg 视频
- apache-spark - 解决火花流中的以下错误
- ios - Swift:使用 Localizable.stringsdict 的本地化字符串中的千位分隔符
- ajax - 数据表中的 WordPress 用户不起作用
- python - 在 Linux 上使用 pexpect 从管道中读取
- openebs - 为什么删除 PVC 后 OpenEBS 挂载路径在主机上仍然可用?
- azure - 搜索查询应包含度量警报类型的“AggregatedValue”和“bin(timestamp, [roundTo])”
- java - Spring Security SAML 错误日志记录引发错误
- haskell - 我的幺半群应该是左偏还是右偏?
- babeljs - 如何列出 @babel/preset-env 包含的转换?