使用 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/