How to use email method in pact-foundation-pact

Best JavaScript code snippet using pact-foundation-pact

EmailChangeTest.ts

Source:EmailChangeTest.ts Github

copy

Full Screen

1import * as EmailUtils from "backend/src/EmailUtils";2import {requireEnvVar} from "backend/src/Env";3import {loadProfile} from "backend/src/Persistence/AccountPersistence";4import {EMAIL_CHANGE_TOKEN_EXPIRATION_TIME} from "backend/src/Persistence/EmailChange";5import {EmailChangeStep1} from "backend/src/ScenarioHandlers/EmailChangeStep1";6import {EmailChangeStep2} from "backend/src/ScenarioHandlers/EmailChangeStep2";7import {Registration} from "backend/src/ScenarioHandlers/Registration";8import * as StringUtils from "backend/src/StringUtils";9import {q, Stub} from "backend/tests/src/TestHelpers";10import {expect} from "chai";11import {AccountCreationSuccess} from "shared/src/Model/Account";12import {UserSession} from "shared/src/Model/UserSession";13import {EmailChangeStep1Result} from "shared/src/Scenarios/EmailChangeStep1";14import {EmailChangeStep2Result} from "shared/src/Scenarios/EmailChangeStep2";15import Sinon = require("sinon");16describe("EmailChange", () => {17 let sendEmailStub: Stub<typeof EmailUtils.sendEmail>;18 beforeEach(() => (sendEmailStub = Sinon.stub(EmailUtils, "sendEmail")));19 afterEach(() => sendEmailStub.restore());20 describe("step 1", () => {21 describe("unhappy paths", () => {22 Object.entries({23 "when not authenticated": {24 input: {newEmail: ""},25 session: {userId: undefined},26 expectedResult: {kind: "NotAuthenticatedError"},27 },28 "when the new email is incorrect": {29 input: {newEmail: "bad-email"},30 session: {userId: 42, email: "some@email.com"},31 expectedResult: {kind: "EmailError", errorCode: "INCORRECT"},32 },33 "when the new email is the same as the old one": {34 input: {newEmail: "some@email.com"},35 session: {userId: 42, email: "some@email.com"},36 expectedResult: {kind: "EmailIsTheSameError"},37 },38 }).forEach(([description, {input, session, expectedResult}]) => {39 context(description, () => {40 it("reports the failure", async () => {41 expect(await EmailChangeStep1(input, session)).to.deep.equal(expectedResult);42 });43 });44 });45 });46 describe("when the email is syntactically correct and different from the old one", () => {47 let result: EmailChangeStep1Result;48 const session = {userId: 42, email: "some@email.com"};49 const input = {newEmail: "new@email.com"};50 let getRandomStringStub: Stub<typeof StringUtils.getRandomString>;51 beforeEach(() => (getRandomStringStub = Sinon.stub(StringUtils, "getRandomString").returns("token")));52 afterEach(() => getRandomStringStub.restore());53 beforeEach(async () => {54 await Registration({fullName: "Joe DOE", email: session.email, password: "secret"}, session);55 sendEmailStub.resetHistory(); // ignore the registration email56 });57 const token = "8715a02588ff190e";58 beforeEach(async () => {59 getRandomStringStub.returns(token);60 result = await EmailChangeStep1(input, session);61 });62 it("does the work", async () => {63 expect(await getEmailChangeRequest(session.userId)).to.deep.equal(64 {current_email: session.email, new_email: input.newEmail, token},65 "records the email change request"66 );67 const containsTheConfirmationLink = Sinon.match(`${requireEnvVar("APP_URL")}/schimbare-email?token=${token}`);68 expect(69 sendEmailStub,70 "sends a message to the new email address to ask confirmation"71 ).to.have.been.calledOnceWithExactly(input.newEmail, "Schimbare email", containsTheConfirmationLink);72 expect(result).to.deep.equal({kind: "EmailChangeConfirmationRequestSent"}, "reports the success");73 });74 async function getEmailChangeRequest(userId: number) {75 const [row] = await q(`76 SELECT current_email, new_email, token77 FROM email_change_requests78 WHERE user_id = ${userId}79 `);80 return row;81 }82 });83 });84 describe("step2", () => {85 describe("unhappy paths", () => {86 Object.entries({87 "when the token is missing": {88 input: {token: ""},89 expectedResult: {kind: "EmailChangeTokenValidationError", errorCode: "REQUIRED"},90 },91 "when the token has invalid length": {92 input: {token: "c0ffee"},93 expectedResult: {kind: "EmailChangeTokenValidationError", errorCode: "BAD_LENGTH"},94 },95 "when the token has the appropriate length but is not registered in the DB": {96 input: {token: "8715a02588ff190e"},97 expectedResult: {kind: "EmailChangeTokenUnrecognizedError"},98 },99 }).forEach(([description, {input, expectedResult}]) => {100 context(description, () => {101 it("reports the failure", async () => {102 expect(await EmailChangeStep2(input, {})).to.deep.equal(expectedResult);103 });104 });105 });106 });107 describe("happy path", () => {108 describe("when the token is registered in the DB", () => {109 const currentEmail = "some@email.com";110 const newEmail = "new@email.com";111 let userId: number;112 let session: UserSession;113 let result: EmailChangeStep2Result;114 beforeEach(async () => {115 const registrationRequest = {fullName: "Joe DOE", email: currentEmail, password: "secret"};116 const registrationResult = (await Registration(registrationRequest, {})) as AccountCreationSuccess;117 userId = registrationResult.id;118 sendEmailStub.resetHistory(); // ignore the registration email119 });120 let time: Sinon.SinonFakeTimers;121 beforeEach(() => (time = Sinon.useFakeTimers()));122 afterEach(() => time.restore());123 let getRandomStringStub: Stub<typeof StringUtils.getRandomString>;124 beforeEach(() => (getRandomStringStub = Sinon.stub(StringUtils, "getRandomString")));125 afterEach(() => getRandomStringStub.restore());126 const expiredToken = "8715a02588ff1901";127 const currentToken = "8715a02588ff1902";128 beforeEach(async () => {129 getRandomStringStub.onFirstCall().returns(expiredToken);130 await EmailChangeStep1({newEmail}, {userId, email: currentEmail});131 time.tick(EMAIL_CHANGE_TOKEN_EXPIRATION_TIME + 1); // To test expiration of old tokens.132 getRandomStringStub.onSecondCall().returns(currentToken);133 await EmailChangeStep1({newEmail}, {userId, email: currentEmail});134 expect(await getEmailChangeRequestCount()).to.equal(2);135 sendEmailStub.resetHistory(); // ignore the request confirmation emails136 });137 beforeEach(async () => {138 session = {userId, email: currentEmail};139 result = await EmailChangeStep2({token: currentToken}, session);140 });141 it("does the work", async () => {142 const tokens = await getCurrentEmailChangeRequestTokens();143 expect(tokens).not.to.include(expiredToken, "purges the expired token");144 expect(tokens).not.to.include(currentToken, "deletes the verified token");145 expect(await loadProfile(userId)).to.have.property("email", newEmail, "changes the email");146 expect(await q(`SELECT * FROM previous_emails`)).to.deep.equal(147 [{email: currentEmail, user_id: userId, timestamp: Date.now()}],148 "records the email change"149 );150 expect(session.email).to.equal(newEmail, "updates the session");151 expect(result).to.deep.equal({kind: "EmailChanged"}, "reports the success");152 });153 async function getEmailChangeRequestCount() {154 const countColumnName = "count";155 const [row] = await q(`156 SELECT COUNT(*) as ${countColumnName}157 FROM email_change_requests158 WHERE current_email = "${currentEmail}"159 `);160 return row[countColumnName];161 }162 async function getCurrentEmailChangeRequestTokens() {163 const rows = await q(`164 SELECT token165 FROM email_change_requests166 WHERE current_email = "${currentEmail}"167 `);168 return rows.map((r) => r.token);169 }170 });171 });172 });...

Full Screen

Full Screen

update-profile.js

Source:update-profile.js Github

copy

Full Screen

1module.exports = {2 friendlyName: 'Update profile',3 description: 'Update the profile for the logged-in user.',4 inputs: {5 fullName: {6 type: 'string'7 },8 emailAddress: {9 type: 'string'10 },11 },12 exits: {13 emailAlreadyInUse: {14 statusCode: 409,15 description: 'The provided email address is already in use.',16 },17 },18 fn: async function (inputs) {19 var newEmailAddress = inputs.emailAddress;20 if (newEmailAddress !== undefined) {21 newEmailAddress = newEmailAddress.toLowerCase();22 }23 // Determine if this request wants to change the current user's email address,24 // revert her pending email address change, modify her pending email address25 // change, or if the email address won't be affected at all.26 var desiredEmailEffect;// ('change-immediately', 'begin-change', 'cancel-pending-change', 'modify-pending-change', or '')27 if (28 newEmailAddress === undefined ||29 (this.req.me.emailStatus !== 'change-requested' && newEmailAddress === this.req.me.emailAddress) ||30 (this.req.me.emailStatus === 'change-requested' && newEmailAddress === this.req.me.emailChangeCandidate)31 ) {32 desiredEmailEffect = '';33 } else if (this.req.me.emailStatus === 'change-requested' && newEmailAddress === this.req.me.emailAddress) {34 desiredEmailEffect = 'cancel-pending-change';35 } else if (this.req.me.emailStatus === 'change-requested' && newEmailAddress !== this.req.me.emailAddress) {36 desiredEmailEffect = 'modify-pending-change';37 } else if (!sails.config.custom.verifyEmailAddresses || this.req.me.emailStatus === 'unconfirmed') {38 desiredEmailEffect = 'change-immediately';39 } else {40 desiredEmailEffect = 'begin-change';41 }42 // If the email address is changing, make sure it is not already being used.43 if (_.contains(['begin-change', 'change-immediately', 'modify-pending-change'], desiredEmailEffect)) {44 let conflictingUser = await User.findOne({45 or: [46 { emailAddress: newEmailAddress },47 { emailChangeCandidate: newEmailAddress }48 ]49 });50 if (conflictingUser) {51 throw 'emailAlreadyInUse';52 }53 }54 // Start building the values to set in the db.55 // (We always set the fullName if provided.)56 var valuesToSet = {57 fullName: inputs.fullName,58 };59 switch (desiredEmailEffect) {60 // Change now61 case 'change-immediately':62 _.extend(valuesToSet, {63 emailAddress: newEmailAddress,64 emailChangeCandidate: '',65 emailProofToken: '',66 emailProofTokenExpiresAt: 0,67 emailStatus: this.req.me.emailStatus === 'unconfirmed' ? 'unconfirmed' : 'confirmed'68 });69 break;70 // Begin new email change, or modify a pending email change71 case 'begin-change':72 case 'modify-pending-change':73 _.extend(valuesToSet, {74 emailChangeCandidate: newEmailAddress,75 emailProofToken: await sails.helpers.strings.random('url-friendly'),76 emailProofTokenExpiresAt: Date.now() + sails.config.custom.emailProofTokenTTL,77 emailStatus: 'change-requested'78 });79 break;80 // Cancel pending email change81 case 'cancel-pending-change':82 _.extend(valuesToSet, {83 emailChangeCandidate: '',84 emailProofToken: '',85 emailProofTokenExpiresAt: 0,86 emailStatus: 'confirmed'87 });88 break;89 // Otherwise, do nothing re: email90 }91 // Save to the db92 await User.updateOne({id: this.req.me.id })93 .set(valuesToSet);94 // If this is an immediate change, and billing features are enabled,95 // then also update the billing email for this user's linked customer entry96 // in the Stripe API to make sure they receive email receipts.97 // > Note: If there was not already a Stripe customer entry for this user,98 // > then one will be set up implicitly, so we'll need to persist it to our99 // > database. (This could happen if Stripe credentials were not configured100 // > at the time this user was originally created.)101 if(desiredEmailEffect === 'change-immediately' && sails.config.custom.enableBillingFeatures) {102 let didNotAlreadyHaveCustomerId = (! this.req.me.stripeCustomerId);103 let stripeCustomerId = await sails.helpers.stripe.saveBillingInfo.with({104 stripeCustomerId: this.req.me.stripeCustomerId,105 emailAddress: newEmailAddress106 }).timeout(5000).retry();107 if (didNotAlreadyHaveCustomerId){108 await User.updateOne({ id: this.req.me.id })109 .set({110 stripeCustomerId111 });112 }113 }114 // If an email address change was requested, and re-confirmation is required,115 // send the "confirm account" email.116 if (desiredEmailEffect === 'begin-change' || desiredEmailEffect === 'modify-pending-change') {117 await sails.helpers.sendTemplateEmail.with({118 to: newEmailAddress,119 subject: 'Your account has been updated',120 template: 'email-verify-new-email',121 templateData: {122 fullName: inputs.fullName||this.req.me.fullName,123 token: valuesToSet.emailProofToken124 }125 });126 }127 }...

Full Screen

Full Screen

email-setting.component.ts

Source:email-setting.component.ts Github

copy

Full Screen

1import { Component, OnDestroy, OnInit } from '@angular/core';2import { FormControl, FormGroup, Validators } from '@angular/forms';3import { Store } from '@ngrx/store';4import { Subscription } from 'rxjs';5import { EmailSettingService } from 'src/services/email-setting.service';6import * as Alert from '../toster/alert';7import * as fromApp from '../store/app.reducer';8import { Router } from '@angular/router';9import { getEmails } from './store/email-setting.selector';10import { getEmailById, loadEmail, updateEmail } from './store/email-setting.actions';11import { Email } from './email.model';12@Component({13 selector: 'app-email-setting',14 templateUrl: './email-setting.component.html',15 styleUrls: ['./email-setting.component.css']16})17export class EmailSettingComponent implements OnInit, OnDestroy {18 private userSub: Subscription;19 emailSettingForm: FormGroup;20 emailSetting: any;21 constructor(private emailService: EmailSettingService,22 private store: Store<fromApp.AppState>,23 private route: Router) { }24 ngOnInit(): void {25 this.userSub = this.store.select('auth')26 .subscribe(user => {27 if(user.user !== null){28 for(var r in user.user._roles){29 if(user.user._roles[r] !== 'admin'){30 this.route.navigate(['/dashboard']);31 Alert.tosterAlert('Access denied !', 'error');32 }33 }34 }35 });36 this.loadEmail();37 this.initEmailForm();38 this.store.select(getEmails);39 this.store.dispatch(loadEmail());40 }41 private loadEmail(){42 this.emailService.getEmail().subscribe( data => {43 if(data){44 this.emailSetting = data;45 }46 });47 }48 private initEmailForm(){49 let id = 1;50 let emailAddress = '';51 let password = '';52 let host = '';53 let port = '';54 let cc = '';55 this.emailSettingForm = new FormGroup({56 'id': new FormControl(id),57 'emailAddress': new FormControl(emailAddress, [Validators.required, Validators.email]),58 'password': new FormControl(password, [Validators.required]),59 'host': new FormControl(host, [Validators.required]),60 'port': new FormControl(port, [Validators.required]),61 'cc': new FormControl(cc, [Validators.required, Validators.email])62 });63 }64 onEditEmail(){65 this.emailService.getEmail()66 .subscribe(data => {67 if(data !== null){68 this.emailSettingForm.patchValue(data);69 }70 });71 // let id = 1;72 // this.store.dispatch(getEmailById({ id }));73 }74 onSubmit(){75 if(!this.emailSettingForm.valid){76 return77 }78 const email = {79 id: 1,80 emailAddress: this.emailSettingForm.value.emailAddress,81 password: this.emailSettingForm.value.password,82 host: this.emailSettingForm.value.host,83 port: this.emailSettingForm.value.port,84 cc: this.emailSettingForm.value.cc,85 updated_Date: null,86 }87 this.emailService.updateEmailSetting(email)88 .subscribe(data => {89 if(data.isUpdated){90 document.getElementById('closeBtn').click();91 Alert.tosterAlert(data.message, 'success');92 this.loadEmail();93 } else {94 Alert.tosterAlert(data.message, 'error');95 }96 });97 // const email: Email = {98 // id: 1,99 // emailAddress: this.emailSettingForm.value.emailAddress,100 // password: this.emailSettingForm.value.password,101 // host: this.emailSettingForm.value.host,102 // port: this.emailSettingForm.value.port,103 // cc: this.emailSettingForm.value.cc,104 // updated_Date: null,105 // }106 //this.store.dispatch(updateEmail({ email }));107 }108 ngOnDestroy(): void {109 if(this.userSub){110 this.userSub.unsubscribe();111 }112 }...

Full Screen

Full Screen

EmailChange.ts

Source:EmailChange.ts Github

copy

Full Screen

1import {EmailError, EmailValidationRules} from "shared/src/Model/Email";2import {EmailChangeStep1Input} from "shared/src/Scenarios/EmailChangeStep1";3import {EmailChangeStep2Input} from "shared/src/Scenarios/EmailChangeStep2";4import {PredicateFn, UserValue, validateWithRules, ValidationMessages} from "shared/src/Utils/Validation";5export type EmailChangeConfirmationRequestSent = {6 kind: "EmailChangeConfirmationRequestSent";7};8export type EmailIsTheSameError = {9 kind: "EmailIsTheSameError";10};11export type EmailChangeRequest = {12 kind: "EmailChangeRequest";13 newEmail: string;14 currentEmail: string;15};16export type RequestCreated = {17 kind: "RequestCreated";18 token: string;19};20export function makeEmailChangeRequest(21 input: EmailChangeStep1Input,22 currentEmail: string23): EmailChangeRequest | EmailError | EmailIsTheSameError {24 const newEmailResult = validateWithRules(input.newEmail, EmailValidationRules);25 if (newEmailResult.kind === "Invalid") {26 return {27 kind: "EmailError",28 errorCode: newEmailResult.validationErrorCode,29 };30 }31 const newEmail = newEmailResult.value;32 if (currentEmail === newEmail) {33 return {34 kind: "EmailIsTheSameError",35 };36 }37 return {38 kind: "EmailChangeRequest",39 newEmail,40 currentEmail,41 };42}43export type EmailChanged = {44 kind: "EmailChanged";45};46export type EmailChangeTokenValidationError = {47 kind: "EmailChangeTokenValidationError";48 errorCode: ChangeEmailTokenErrorCode;49};50export type EmailChangeTokenUnrecognizedError = {51 kind: "EmailChangeTokenUnrecognizedError";52};53export type EmailChangeConfirmation = {54 kind: "EmailChangeConfirmation";55 token: string;56};57export type EmailChangeTokenVerified = {58 kind: "EmailChangeTokenVerified";59 userId: number;60 newEmail: string;61 currentEmail: string;62};63export type ChangeEmailTokenErrorCode = "REQUIRED" | "BAD_LENGTH";64export const EMAIL_CHANGE_TOKEN_LENGTH = 16;65export const ChangeEmailTokenValidationRules: Record<ChangeEmailTokenErrorCode, PredicateFn> = {66 REQUIRED: (text: UserValue) => !!text && text.trim().length > 0,67 BAD_LENGTH: (text: UserValue) => !!text && text.trim().length === EMAIL_CHANGE_TOKEN_LENGTH,68};69export const ChangeEmailTokenErrorMessages: ValidationMessages<typeof ChangeEmailTokenValidationRules> = {70 REQUIRED: "Tokenul de schimbare a adresei de email lipsește",71 BAD_LENGTH: "Tokenul de schimbare a adresei de email a nu corespunde după lungime",72};73export function makeEmailChangeConfirmation(74 input: EmailChangeStep2Input75): EmailChangeConfirmation | EmailChangeTokenValidationError {76 const validationResult = validateWithRules(input.token, ChangeEmailTokenValidationRules);77 if (validationResult.kind === "Invalid") {78 return {79 kind: "EmailChangeTokenValidationError",80 errorCode: validationResult.validationErrorCode,81 };82 }83 return {84 kind: "EmailChangeConfirmation",85 token: validationResult.value,86 };...

Full Screen

Full Screen

email.server.controller.js

Source:email.server.controller.js Github

copy

Full Screen

1const Email = require('../model/email.server.model');2const logger = require('../../config/logger');3const emailUtil = require('../../util/send_email');4const checkForValidMongoId = new RegExp('^[0-9a-fA-F]{24}$');5module.exports.renderForm = function(req, res) {6 res.send('API Details');7};8module.exports.sendEmail = function(req, res) {9 const email = new Email(req.body);10 email.save()11 .then(() => {12 sendEmail();13 })14 .catch(e => res.json({success: false, error: e.message}));15 function sendEmail() {16 emailUtil.sendEmail({17 id: email._id,18 to: email.to,19 subject: email.subject,20 html: email.html || ''21 }, emailSentStatus );22 }23 function emailSentStatus(error) {24 if (error) {25 email.status = 'failed';26 email.error = error;27 email.save();28 logger.error(error);29 res.json({success: false, error: error});30 } else{31 res.json({success: true, id : email.id});32 }33 }34};35module.exports.emailOpen = function(req, res) {36 if(checkForValidMongoId.test(req.params.id)) {37 Email.findOne({ _id: req.params.id, status: {$ne: 'opened'} }).then((email) => {38 if(email){39 email.openedDate = new Date();40 email.status = 'opened';41 email.save();42 acknowledge(email);43 }44 });45 }46 res.redirect(`/${process.env.IMAGE_NAME}`);47};48function acknowledge(emailDetails) {49 const options = {50 to: process.env.EMAIL,51 subject: `${emailDetails.to} has opened email`,52 html: `${emailDetails.to} has opened email an with the subject line <b>${emailDetails.subject}</b>53 <p>Email Read Time: <b>${emailDetails.openedDate}</b></p>`54 };55 emailUtil.sendEmail(options, function(error) {56 if(error) {57 logger.error(error);58 } else {59 logger.info('ACK email has been sent');60 }61 });...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pact-foundation-pact automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful