Skip to content

Instantly share code, notes, and snippets.

@myquery
Forked from Pompeu/sendgrid.js
Created February 15, 2022 16:59
Show Gist options
  • Save myquery/5d5617c60bc7b56db6fbcf2e47b63e24 to your computer and use it in GitHub Desktop.
Save myquery/5d5617c60bc7b56db6fbcf2e47b63e24 to your computer and use it in GitHub Desktop.
try mock sendgrid
'use strict';
const sendgrid = require('sendgrid')(process.env.MAIL_KEY || 'may secrete key');
function Mailer () {
this.sendMail = body => {
if(!this.verifyMailbody(body)) {
throw new TypeError('invalid body');
}
return new Promise((resolve, reject) => {
return sendgrid.send({
body
}, (err, json) => {
err ? reject(err) : resolve(json);
});
});
};
this.verifyMailbody = body => {
return Object
.keys(body)
.map(verifyProperts)
.reduce(b => b);
};
const propertys = ['to', 'from', 'subject', 'text'];
function verifyProperts(body, index) {
return propertys[index] === body;
}
}
module.exports = Mailer;
///testes
'use strict';
const chai = require('chai');
const expect = chai.expect;
const chaiAsPromise = require('chai-as-promised');
chai.use(chaiAsPromise);
const Mailer = require('../mailer/mailer');
const sinon = require('sinon');
require('sinon-as-promised');
describe('mailer', () => {
let mail = null;
let mailer = null;
before(() => {
mailer = new Mailer();
mail = {
to : 'example@example.com',
from : 'other@example.com',
subject : 'Hello World',
text : 'My first email through SendGrid.'
};
});
describe('mailer', () => {
it('should be mailer has method send mail', () => {
expect(mailer).to.have.property('sendMail');
});
it('should be mailer mail has method then', () => {
expect(mailer.sendMail(mail)).to.be.instanceof(Promise);
});
it('should be throw error if body missing properts', () => {
expect(() => {
mailer.sendMail();
}).to.throw(TypeError, /body no has to,from,subject,text/);
});
it('should be method sendiMail recive a body', () => {
const spy = sinon.spy(mailer, 'sendMail');
spy.withArgs(mail);
mailer.sendMail(mail);
expect(spy.withArgs(mail).calledOnce).to.be.true;
});
it('should be method sendiMail throw if invalid body ', () => {
const mailFail = {
a: 'example@example.com',
from: 'other@example.com',
subject: 'Hello World',
text: 'My first email through SendGrid.'
};
expect(function () {
mailer.sendMail(mailFail);
}).to.throw(TypeError, /^invalid body$/);
});
it('should be method sendMail send a mail with success', done => {
const mailer = new Mailer();
const mock = sinon.mock(mailer);
const success = {success : 'mail success'};
mock.expects('sendMail')
.once()
.withArgs(mail)
.resolves(success);
expect(mailer.sendMail(mail))
.to
.eventually
.equal(success)
.notify(done);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment