我正在使用AVA框架(https://github.com/avajs/ava/blob/HEAD/docs/01-writing-tests.md) 在NodeJS编写的GCP上测试云功能。 我正在尝试对云函数内部的内部函数进行单元测试。
我的测试代码如下:
const test = require(`ava`);
const uuid = require(`uuid`);
const sinon = require(`sinon`);
const triggerResultsService = require(`..`).triggerResultsService;
const consoleLog = sinon.stub(console, 'log');
const sendToTransferService = require(`..`).triggerResultsService.sendToTransferService;
test('resolves with unicorn', t => {
const filename = uuid.v4();
sendToTransferService(filename, () =>{
});
return Promise().then(result => {
t.is(result, 'unicorn');
});
});
“我的云”功能代码如下:
/**
* Generic background Cloud Function to be triggered by Cloud Storage.
*
* @param {object} event The Cloud Functions event.
* @param {function} callback The callback function.
*/
var request = require("request");
exports.triggerResultsService = (event, callback) => {
var file = event.data;
var fileName = file.name.substr(file.name.lastIndexOf('/')).toLowerCase().trim();
if(!fileName.includes('temp-') && fileName.includes('.csv.gz')) {
console.log("file name is in correct location, sending options");
sendToTransferService(file);
sendStatusEmail("Transfer File Call successful");
};
callback();
};
function sendToTransferService(file) {
var options = {
method: 'POST',
uri: process.env.TRANSFER_SERVICE_URL,
body: {
fileName: file.name,
bucketName: file.bucket
},
json: true
};
return new Promise(function (resolve, reject) {
request(options, function (err, resp) {
if (err) {
console.log(err);
return reject({err: err});
}
return resolve({responsebody:resp.body});
});
});
}
function sendStatusEmail(statusMessage) {
var options = {
method: 'POST',
uri: process.env.EMAIL_NOTIFICATION_URL,
body: {
from: process.env.EMAIL_FROM,
to: [process.env.SLACK_EMAIL],
cc: [''],
bcc: [''],
subject: process.env.EMAIL_SUBJECT,
body: statusMessage
},
json: true
};
return new Promise(function (resolve, reject) {
request(options, function (err, resp) {
if (err) {
console.log(err);
return reject({err: err});
}
return resolve({responsebody:resp.body});
});
});
}
我无法使用sendToTransferService函数。 任何想法我需要/声明什么
预先感谢
答案 0 :(得分:1)
我认为您最简单的方法是将该函数转换为自己的模块,然后从那里导出它。导入该模块的任何其他代码(包括您的Cloud Functions代码)都可以使用它。