У меня есть следующий код, и я пытаюсь создать модульный тест, чтобы убедиться, что функция sendToGoogle работает, поэтому я заглушаю метод send gmail.users.messages и ожидаю, что метод будет вызван методом sendToGoogle, но я получил эту ошибку
AssertionError: ожидаемая отправка была вызвана хотя бы один раз, но никогда не вызывалась
// email.js
const helper = require('./helper')
/**
* sendEmail - sends an email to a given address
*
* @param {String} to - The address of the recipient.
* @param {String} from - The address of the sender.
* @param {String} subject - subject of the email.
* @param {String} bodyText - text of the email.
**/
function sendEmail(to, from, subject, bodyText) {
const oAuthClient = helper.getAuth(process.env.CLIENT_ID, process.env.PRIVATE_KEY, from);
const emailLines = helper.createEmail(to, from, subject, bodyText);
helper.sendToGoogle(oAuthClient, from, emailLines);
}
module.exports.sendEmail = sendEmail;
здесь есть помощник.js, который содержит мой код
// helper.js
const {google} = require('googleapis');
const base64 = require('base-64');
const gmail = google.gmail("v1");
/**
* createEmail - createEmail an email message
*
* @param {String} to - The address of the recipient.
* @param {String} from - The address of the sender.
* @param {String} subject - subject of the email.
* @param {String} bodyText - text of the email.
* @return {String} - Message to send.
**/
const createEmail = function (to, from, subject, bodyText) {
const emailLines = ["Content-Type: text/plain; charset=\"UTF-8\"\n",
"MIME-Version: 1.0\n",
"Content-Transfer-Encoding: 7bit\n",
"to: ", to, "\n",
"from: ", from, "\n",
"subject: ", subject, "\n\n",
bodyText
].join('')
const messageBase64 = base64.encode(emailLines.trim()).replace(/\+/g, '-').replace(/\//g, '_');
return messageBase64
}
/**
*
*
* @param {String} clientKey
* @param {String} privateKey
* @param {String} from
* @returns
*/
const getAuth = function (clientKey, privateKey, from) {
return new google.auth.JWT(
clientKey,
null,
privateKey,
['https://www.googleapis.com/auth/gmail.send'],
from
);
}
/**
* @param {String} oAuthClient
* @param {String} from
* @param {String} message
*/
const sendToGoogle = function (oAuthClient, from, message) {
console.log("sendtogoogle calllled")
gmail.users.messages.send({
auth: oAuthClient,
userId: from,
resource: {
raw: message
}
}, function (err, resp) {
if (!err) {
return resp
}
console.error(err)
});
}
module.exports.createEmail = createEmail
module.exports.getAuth = getAuth
module.exports.sendToGoogle = sendToGoogle
, и это файл unittest
// email.spec.js
it ("send to gmail",function(){
const gmail = google.gmail("v1");
const SendStub = sinon.stub(gmail.users.messages, 'send').returns('test')
const result = helper.sendToGoogle("oAuthClient", from,"message")
SendStub.should.have.been.called
})
Ваша помощь приветствуется.