How to use promise.reject method in sinon

Best JavaScript code snippet using sinon

user.js

Source:user.js Github

copy

Full Screen

1// Check if a user is logged in on the session cookie2export const checkCookie = (app) => {3 const url = "/session/check-session";4 fetch(url)5 .then(res => {6 if (res.ok) {7 return res.json();8 }9 })10 .then(json => {11 if (json) {12 app.setState({ currentUser: json, userUpdated: false });13 } else {14 app.setState({ currentUser: null, userUpdated: false });15 }16 })17 .catch();18}19// Send request to server to login a user20export const login = async (loginObject) => {21 const url = "/session/login";22 // Create request23 const request = new Request(url, {24 method: "POST",25 body: JSON.stringify(loginObject),26 headers: {27 "Accept": "application/json, text/plan, */*",28 "Content-Type": "application/json"29 }30 });31 // Send request32 try {33 const res = await fetch(request);34 if (res.ok) {35 const body = await res.json();36 if (body !== undefined) {37 return body;38 } else {39 return Promise.reject(new Error('Login Response Empty'));40 }41 } else {42 if (res.status === 401) {43 return Promise.reject('credentials')44 }45 return Promise.reject(new Error('Internal Server Error'));46 }47 } catch (error) {48 console.error(error);49 return Promise.reject(error);50 }51}52// A function to send a GET request to logout the current user53export const logout = async (app) => {54 const url = "/session/logout";55 // Create request56 const request = new Request(url, {57 method: "POST",58 headers: {59 "Accept": "application/json, text/plan, */*",60 "Content-Type": "application/json"61 }62 });63 try {64 const res = await fetch(request);65 if (res.ok) {66 app.setState({67 userUpdated: true68 });69 } else {70 return Promise.reject(new Error('Internal Server Error'));71 }72 } catch (error) {73 console.error(error);74 return Promise.reject(error);75 }76};77export const getUser = async (username) => {78 const url = `/api/users/${username}`;79 // Send request80 try {81 const res = await fetch(url);82 const body = await res.json();83 if (res.ok) {84 if (body !== undefined) {85 // Send user object86 return body;87 } else {88 return Promise.reject(new Error('User Account Response Empty'));89 }90 } else {91 if (res.status === 400) {92 return Promise.reject("username");93 }94 return Promise.reject(new Error(body));95 }96 } catch (error) {97 console.error(error);98 return Promise.reject(error);99 }100}101export const registerUser = async (userObject) => {102 const url = `/api/users`;103 // Create request104 const request = new Request(url, {105 method: "POST",106 body: JSON.stringify({ userObject: userObject }),107 headers: {108 "Accept": "application/json, text/plan, */*",109 "Content-Type": "application/json"110 }111 });112 // Send request113 try {114 const res = await fetch(request);115 if (res.ok) {116 const body = await res.json();117 if (body !== undefined) {118 // Resolve promise119 return true;120 } else {121 return Promise.reject(new Error('Register Profile Response Empty'));122 }123 } else {124 switch (res.status) {125 case 400:126 case 403:127 const body = await res.json();128 console.error("Error creating user.");129 return Promise.reject({ validationError: body });130 case 409:131 return Promise.reject('exists');132 default:133 return Promise.reject(new Error("Internal Server Error"));134 }135 }136 } catch (error) {137 console.error(error);138 return Promise.reject(error);139 }140}141export const registerProfile = async (username, profileObject) => {142 const url = `/api/users/${username}/profile`;143 // Create request144 const request = new Request(url, {145 method: "PUT",146 body: JSON.stringify({ profile: profileObject }),147 headers: {148 "Accept": "application/json, text/plan, */*",149 "Content-Type": "application/json"150 }151 });152 // Send request153 try {154 const res = await fetch(request);155 if (res.ok) {156 const body = await res.json();157 if (body !== undefined) {158 // Get user object with newly created profile159 const updatedUser = await getUser(username);160 if (!updatedUser) {161 console.error('Updated user retrieved was empty.');162 return Promise.reject();163 } else {164 // Return the updated user object165 return updatedUser;166 }167 } else {168 return Promise.reject(new Error('Register Profile Response Empty'));169 }170 } else {171 if (res.status === 400) {172 const body = await res.json();173 console.error("Error creating profile.");174 return Promise.reject({ validationError: body });175 } else if (res.status === 401) {176 return Promise.reject('unauthorized');177 }178 return Promise.reject(new Error("Internal Server Error"));179 }180 } catch (error) {181 console.error(error);182 return Promise.reject(error);183 }184}185export const updateUser = async (username, userObject) => {186 const url = `/api/users/${username}`;187 // Create request188 const request = new Request(url, {189 method: "PATCH",190 body: JSON.stringify({ props: userObject }),191 headers: {192 "Accept": "application/json, text/plan, */*",193 "Content-Type": "application/json"194 }195 });196 // Send request197 try {198 const res = await fetch(request);199 if (res.ok) {200 const body = await res.json();201 if (body !== undefined) {202 // Return the updated user object203 return body;204 } else {205 return Promise.reject(new Error('Update User Response Empty'));206 }207 } else {208 switch (res.status) {209 case 400:210 case 403:211 case 404:212 const body = await res.json();213 console.error("Error updating user.");214 return Promise.reject({ validationError: body });215 case 401:216 return Promise.reject('unauthorized');217 case 409:218 return Promise.reject('exists');219 default:220 return Promise.reject(new Error("Internal Server Error"));221 }222 }223 } catch (error) {224 console.error(error);225 return Promise.reject(error);226 }227}228export const updateProfile = async (username, profileObject) => {229 const url = `/api/users/${username}/profile`;230 // Create request231 const request = new Request(url, {232 method: "PATCH",233 body: JSON.stringify({ props: profileObject }),234 headers: {235 "Accept": "application/json, text/plan, */*",236 "Content-Type": "application/json"237 }238 });239 // Send request240 try {241 const res = await fetch(request);242 if (res.ok) {243 const body = await res.json();244 if (body !== undefined) {245 // Return the updated profile object246 return body;247 } else {248 return Promise.reject(new Error('Update Profile Response Empty'));249 }250 } else {251 switch (res.status) {252 case 400:253 case 403:254 case 404:255 const body = await res.json();256 console.error("Error updating profile.");257 return Promise.reject({ validationError: body });258 case 401:259 return Promise.reject('unauthorized');260 case 409:261 return Promise.reject('exists');262 default:263 return Promise.reject(new Error("Internal Server Error"));264 }265 }266 } catch (error) {267 console.error(error);268 return Promise.reject(error);269 }...

Full Screen

Full Screen

reporting.js

Source:reporting.js Github

copy

Full Screen

1'use strict';2const https = require('https');3function Reporting(credentials) {4 this._post = function (opts, path) {5 return new Promise(function (resolve, reject) {6 opts['username'] = credentials['username'];7 opts['password'] = credentials['passcode'];8 var postData = JSON.stringify(opts);9 var params = {10 host: 'a.upwire.com',11 port: 443,12 method: 'POST',13 path: path,14 headers: { "Content-Type": "application/json", "Content-Length": postData.length },15 }16 const req = https.request(params, (res) => {17 if (res.statusCode < 200 || res.statusCode > 299) {18 reject('Request failed, status code: ' + res.statusCode);19 }20 const body = [];21 res.on('data', (chunk) => body.push(chunk));22 res.on('end', () => resolve(body.join('')));23 });24 req.on('error', (err) => reject(err))25 req.write(postData);26 req.end();27 });28 };29}30Reporting.prototype.getMasterJob = function (opts) {31 this.opts = opts;32 if (typeof this.opts !== 'object' ) {33 return Promise.reject("options not parsed");34 }35 if (!this.opts.hasOwnProperty('jobnumber')) {36 return Promise.reject("jobnumber missing from options");37 }38 if (typeof this.opts['jobnumber'] !== 'string') {39 return Promise.reject("jobnumber must be an string");40 }41 this.opts['action'] = 'getMasterJob';42 return this._post(this.opts, '/webuiapi/masterDataHandler.json');43};44Reporting.prototype.listMasterJobs = function (opts) {45 this.opts = opts;46 if (typeof this.opts !== 'object' ) {47 return Promise.reject("options not parsed");48 }49 50 if (!this.opts.hasOwnProperty('limit')) {51 return Promise.reject("limit missing from options");52 }53 if (typeof this.opts['limit'] !== 'number') {54 return Promise.reject("limit must be an number");55 }56 this.opts['action'] = 'listmasterjobs';57 return this._post(this.opts, '/webuiapi/masterDataHandler.json');58};59Reporting.prototype.getMasterData = function (opts) {60 this.opts = opts;61 if (typeof this.opts !== 'object' ) {62 return Promise.reject("options not parsed");63 }64 if (!this.opts.hasOwnProperty('jobnumber')) {65 return Promise.reject("jobnumber missing from options");66 }67 if (typeof this.opts['jobnumber'] !== 'string') {68 return Promise.reject("jobnumber must be an string");69 }70 this.opts['action'] = 'getjobdata';71 return this._post(this.opts, '/webuiapi/masterDataHandler.json');72};73Reporting.prototype.getMasterStats = function (opts) {74 this.opts = opts;75 if (typeof this.opts !== 'object' ) {76 return Promise.reject("options not parsed");77 }78 if (!this.opts.hasOwnProperty('jobnumber')) {79 return Promise.reject("jobnumber missing from options");80 }81 if (typeof this.opts['jobnumber'] !== 'string') {82 return Promise.reject("jobnumber must be an string");83 }84 this.opts['action'] = 'getmasterstats';85 return this._post(this.opts, '/webuiapi/masterDataHandler.json');86};87Reporting.prototype.getSmsJobStats = function (opts) {88 this.opts = opts;89 if (typeof this.opts !== 'object' ) {90 return Promise.reject("options not parsed");91 }92 if (!this.opts.hasOwnProperty('jobnumber')) {93 return Promise.reject("jobnumber missing from options");94 }95 if (typeof this.opts['jobnumber'] !== 'string') {96 return Promise.reject("jobnumber must be an string");97 }98 this.opts['action'] = 'getsmsjobstats';99 return this._post(this.opts, '/webuiapi/masterDataHandler.json');100};101Reporting.prototype.getVoiceJobStats = function (opts) {102 this.opts = opts;103 if (typeof this.opts !== 'object' ) {104 return Promise.reject("options not parsed");105 }106 if (!this.opts.hasOwnProperty('jobnumber')) {107 return Promise.reject("jobnumber missing from options");108 }109 if (typeof this.opts['jobnumber'] !== 'string') {110 return Promise.reject("jobnumber must be an string");111 }112 this.opts['action'] = 'getvoicejobstats';113 return this._post(this.opts, '/webuiapi/masterDataHandler.json');114};115Reporting.prototype.getVoiceJobResponses = function (opts) {116 this.opts = opts;117 if (typeof this.opts !== 'object' ) {118 return Promise.reject("options not parsed");119 }120 if (!this.opts.hasOwnProperty('jobnumber')) {121 return Promise.reject("jobnumber missing from options");122 }123 if (typeof this.opts['jobnumber'] !== 'string') {124 return Promise.reject("jobnumber must be an string");125 }126 this.opts['action'] = 'getvoiceresponses';127 this.opts['resultType'] = 'counts';128 return this._post(this.opts, '/webuiapi/masterDataHandler.json');129};130Reporting.prototype.getEmailJobStats = function (opts) {131 this.opts = opts;132 133 if (typeof this.opts !== 'object' ) {134 return Promise.reject("options not parsed");135 }136 if (!this.opts.hasOwnProperty('jobnumber')) {137 return Promise.reject("jobnumber missing from options");138 }139 if (typeof this.opts['jobnumber'] !== 'string') {140 return Promise.reject("jobnumber must be an string");141 }142 this.opts['action'] = 'getemailjobstats';143 return this._post(this.opts, '/webuiapi/masterDataHandler.json');144};145Reporting.prototype.smsReportByReference = function (opts) {146 this.opts = opts;147 if (typeof this.opts !== 'object' ) {148 return Promise.reject("options not parsed");149 }150 if (!this.opts.hasOwnProperty('reference')) {151 return Promise.reject("reference missing from options");152 }153 if (typeof this.opts['reference'] !== 'string') {154 return Promise.reject("reference must be an string");155 }156 157 if (!this.opts.hasOwnProperty('limit')) {158 return Promise.reject("limit missing from options");159 }160 if (typeof this.opts['limit'] !== 'string') {161 return Promise.reject("limit must be an string");162 }163 this.opts['action'] = 'getbyreference';164 return this._post(this.opts, '/zsms/reports.json');165};166Reporting.prototype.smsReportByJobNumber = function (opts) {167 this.opts = opts;168 if (typeof this.opts !== 'object' ) {169 return Promise.reject("options not parsed");170 }171 if (!this.opts.hasOwnProperty('jobNumber')) {172 return Promise.reject("jobNumber missing from options");173 }174 if (typeof this.opts['jobNumber'] !== 'string') {175 return Promise.reject("jobNumber must be an string");176 }177 if (!this.opts.hasOwnProperty('limit')) {178 return Promise.reject("limit missing from options");179 }180 if (typeof this.opts['limit'] !== 'string') {181 return Promise.reject("limit must be an string");182 }183 this.opts['action'] = 'getbyjobnumber';184 return this._post(this.opts, '/zsms/reports.json');185};186Reporting.prototype.smsReportJobStats = function (opts) {187 this.opts = opts;188 if (typeof this.opts !== 'object' ) {189 return Promise.reject("options not parsed");190 }191 if (!this.opts.hasOwnProperty('jobNumber')) {192 return Promise.reject("jobNumber missing from options");193 }194 if (typeof this.opts['jobNumber'] !== 'string') {195 return Promise.reject("jobNumber must be an string");196 }197 if (!this.opts.hasOwnProperty('limit')) {198 return Promise.reject("limit missing from options");199 }200 if (typeof this.opts['limit'] !== 'string') {201 return Promise.reject("limit must be an string");202 }203 this.opts['action'] = 'getsmsjobstats';204 return this._post(this.opts, '/zsms/reports.json');205};...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const exchange = (function() {2 const USER_COOKIE = '__astra-exchange-user'3 const getCookie = name => {4 const cookies = document.cookie.match(`(^|[^;]+)\\s*${name}\\s*=\\s*([^;]+)`)5 return cookies ? cookies.pop() : undefined6 }7 const setCookie = (name, value) =>8 document.cookie = `${name}=${value}; expires=Sat, 13 Sep 275760 00:00:00 GMT`9 const removeCookie = name =>10 document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT`11 const getCurrentUser = () => {12 const user = getCookie(USER_COOKIE)13 return user ? JSON.parse(user) : undefined14 }15 this.currentUser = getCurrentUser()16 this.users = () =>17 fetch('https://us-central1-astra-exchange.cloudfunctions.net/users').then(response =>18 response.json().catch(() =>19 Promise.reject({ status: 500, message: 'Unknown error. Please try again' })20 )21 )22 this.transact = (pin, from, to, amount, message = undefined) => {23 if (typeof pin !== 'string')24 return Promise.reject({ status: 400, message: '\'pin\' must be a string (parameter 1)' })25 if (pin.length !== 4)26 return Promise.reject({ status: 400, message: '\'pin\' must be 4 characters long (parameter 1)' })27 if (typeof from !== 'string')28 return Promise.reject({ status: 400, message: '\'from\' must be a string (parameter 2)' })29 if (typeof to !== 'string')30 return Promise.reject({ status: 400, message: '\'to\' must be a string (parameter 3)' })31 if (typeof amount !== 'number')32 return Promise.reject({ status: 400, message: '\'amount\' must be a number (parameter 4)' })33 if (!(typeof message === 'string' || message === null || message === undefined))34 return Promise.reject({ status: 400, message: '\'message\' must be a string, null, undefined, or left blank (parameter 5)' })35 return fetch(`https://us-central1-astra-exchange.cloudfunctions.net/transact?pin=${pin}&from=${from}&to=${to}&amount=${amount}${message ? `&message=${message}` : ''}`).then(response => {36 switch (response.status) {37 case 200:38 return Promise.resolve()39 case 400:40 return Promise.reject({ status: 400, message: 'Invalid parameters' })41 case 404:42 return Promise.reject({ status: 404, message: 'Invalid user ID' })43 case 403:44 return Promise.reject({ status: 403, message: 'Insufficient balance' })45 case 401:46 return Promise.reject({ status: 401, message: 'Invalid pin' })47 default:48 return Promise.reject({ status: 500, message: 'Unknown error. Please try again' })49 }50 })51 }52 this.userWithId = (id, pin = undefined) => {53 if (typeof id !== 'string')54 return Promise.reject({ status: 400, message: '\'id\' must be a string (parameter 1)' })55 if (!(typeof pin === 'string' || pin === null || pin === undefined))56 return Promise.reject({ status: 400, message: '\'pin\' must be a string, null, undefined, or left blank (parameter 2)' })57 if (typeof pin === 'string' && pin.length !== 4)58 return Promise.reject({ status: 400, message: '\'pin\' must be 4 characters long (parameter 2)' })59 return fetch(`https://us-central1-astra-exchange.cloudfunctions.net/user?id=${id}${pin ? `&pin=${pin}` : ''}`).then(response => {60 switch (response.status) {61 case 200:62 return response.json().catch(() =>63 Promise.reject({ status: 500, message: 'Unknown error. Please try again' })64 )65 case 400:66 return Promise.reject({ status: 400, message: 'Invalid parameters' })67 case 404:68 return Promise.reject({ status: 404, message: 'Invalid user ID' })69 case 401:70 return Promise.reject({ status: 401, message: 'Invalid pin' })71 default:72 return Promise.reject({ status: 500, message: 'Unknown error. Please try again' })73 }74 })75 }76 this.userWithEmail = (email, pin = undefined) => {77 if (typeof email !== 'string')78 return Promise.reject({ status: 400, message: '\'email\' must be a string (parameter 1)' })79 if (!(typeof pin === 'string' || pin === null || pin === undefined))80 return Promise.reject({ status: 400, message: '\'pin\' must be a string, null, undefined, or left blank (parameter 2)' })81 if (typeof pin === 'string' && pin.length !== 4)82 return Promise.reject({ status: 400, message: '\'pin\' must be 4 characters long (parameter 2)' })83 return fetch(`https://us-central1-astra-exchange.cloudfunctions.net/user?email=${email}${pin ? `&pin=${pin}` : ''}`).then(response => {84 switch (response.status) {85 case 200:86 return response.json().catch(() =>87 Promise.reject({ status: 500, message: 'Unknown error. Please try again' })88 )89 case 400:90 return Promise.reject({ status: 400, message: 'Invalid parameters' })91 case 404:92 return Promise.reject({ status: 404, message: 'Invalid email' })93 case 401:94 return Promise.reject({ status: 401, message: 'Invalid pin' })95 default:96 return Promise.reject({ status: 500, message: 'Unknown error. Please try again' })97 }98 })99 }100 this.transactions = (id, pin) => {101 if (typeof id !== 'string')102 return Promise.reject({ status: 400, message: '\'id\' must be a string (parameter 1)' })103 if (typeof pin !== 'string')104 return Promise.reject({ status: 400, message: '\'pin\' must be a string (parameter 2)' })105 if (pin.length !== 4)106 return Promise.reject({ status: 400, message: '\'pin\' must be 4 characters long (parameter 2)' })107 return fetch(`https://us-central1-astra-exchange.cloudfunctions.net/transactions?id=${id}&pin=${pin}`).then(response => {108 switch (response.status) {109 case 200:110 return response.json().then(objects =>111 objects.map(json =>112 Object.assign(json, { time: new Date(Date.parse(json.time)) })113 )114 ).catch(() =>115 Promise.reject({ status: 500, message: 'Unknown error. Please try again' })116 )117 case 400:118 return Promise.reject({ status: 400, message: 'Invalid parameters' })119 case 404:120 return Promise.reject({ status: 404, message: 'Invalid user ID' })121 case 401:122 return Promise.reject({ status: 401, message: 'Invalid pin' })123 default:124 return Promise.reject({ status: 500, message: 'Unknown error. Please try again' })125 }126 })127 }128 this.isSignedIn = () =>129 currentUser !== undefined130 this.signIn = (email, pin) => {131 if (typeof email !== 'string')132 return Promise.reject({ status: 400, message: '\'email\' must be a string (parameter 1)' })133 if (typeof pin !== 'string')134 return Promise.reject({ status: 400, message: '\'pin\' must be a string (parameter 2)' })135 if (pin.length !== 4)136 return Promise.reject({ status: 400, message: '\'pin\' must be 4 characters long (parameter 2)' })137 return userWithEmail(email, pin).then(user => {138 setCookie(USER_COOKIE, JSON.stringify(user))139 return currentUser = user140 })141 }142 this.signOut = () => {143 removeCookie(USER_COOKIE)144 currentUser = undefined145 }146 this.reloadCurrentUser = () =>147 currentUser ? signIn(currentUser.email, currentUser.pin) : Promise.resolve(undefined)148 return this...

Full Screen

Full Screen

AlarmContext.js

Source:AlarmContext.js Github

copy

Full Screen

1/**2 * Copyright 2004-present Facebook. All Rights Reserved.3 *4 * This source code is licensed under the BSD-style license found in the5 * LICENSE file in the root directory of this source tree.6 *7 * @flow strict-local8 * @format9 *10 */11import React from 'react';12import {PROMETHEUS_RULE_TYPE} from './rules/PrometheusEditor/getRuleInterface';13import type {ApiUtil} from './AlarmsApi';14import type {FiringAlarm, Labels} from './AlarmAPIType';15import type {RuleInterfaceMap} from './rules/RuleInterface';16export type AlarmContext = {|17 apiUtil: ApiUtil,18 filterLabels?: (labels: Labels) => Labels,19 ruleMap: RuleInterfaceMap<*>,20 getAlertType?: ?GetAlertType,21 // feature flags22 thresholdEditorEnabled?: boolean,23 alertManagerGlobalConfigEnabled?: boolean,24|};25/***26 * Determine the type of alert based on its labels/annotations. Since all27 * alerts come from alertmanager, regardless of source, we can only determine28 * the source by inspecting the labels/annotations.29 */30export type GetAlertType = (31 alert: FiringAlarm,32 ruleMap?: RuleInterfaceMap<mixed>,33) => $Keys<RuleInterfaceMap<mixed>>;34const emptyApiUtil = {35 useAlarmsApi: () => ({36 response: null,37 error: new Error('not implemented'),38 isLoading: false,39 }),40 viewFiringAlerts: (..._) => Promise.reject('not implemented'),41 viewMatchingAlerts: (..._) => Promise.reject('not implemented'),42 createAlertRule: (..._) => Promise.reject('not implemented'),43 editAlertRule: (..._) => Promise.reject('not implemented'),44 getAlertRules: (..._) => Promise.reject('not implemented'),45 deleteAlertRule: (..._) => Promise.reject('not implemented'),46 getSuppressions: (..._) => Promise.reject('not implemented'),47 createReceiver: (..._) => Promise.reject('not implemented'),48 editReceiver: (..._) => Promise.reject('not implemented'),49 getReceivers: (..._) => Promise.reject('not implemented'),50 deleteReceiver: (..._) => Promise.reject('not implemented'),51 getRouteTree: (..._) => Promise.reject('not implemented'),52 editRouteTree: (..._) => Promise.reject('not implemented'),53 getMetricSeries: (..._) => Promise.reject('not implemented'),54 getGlobalConfig: _ => Promise.reject('not implemented'),55 editGlobalConfig: _ => Promise.reject('not implemented'),56 getTenants: _ => Promise.reject('not implemented'),57 getAlertmanagerTenancy: _ => Promise.reject('not implemented'),58 getPrometheusTenancy: _ => Promise.reject('not implemented'),59};60const context = React.createContext<AlarmContext>({61 apiUtil: emptyApiUtil,62 filterLabels: x => x,63 ruleMap: {},64 getAlertType: _ => PROMETHEUS_RULE_TYPE,65 thresholdEditorEnabled: false,66 alertManagerGlobalConfigEnabled: false,67});68export function useAlarmContext() {69 return React.useContext(context);70}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var Promise = require('bluebird');3var chai = require('chai');4var assert = chai.assert;5var expect = chai.expect;6var should = chai.should();7describe('Promises', function() {8 it('should return a rejected promise', function() {9 var spy = sinon.spy();10 var promise = Promise.reject(new Error('error'));11 promise.then(spy);12 spy.called.should.be.false;13 });14});

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var Promise = require('bluebird');3var chai = require('chai');4var assert = chai.assert;5var expect = chai.expect;6var should = chai.should();7describe('Promises', function() {8 it('should return a rejected promise', function() {9 var spy = sinon.spy();10 var promise = Promise.reject(new Error('error'));11 promise.then(spy);12 spy.called.should.be.false;13 });14});

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var Promise = require('bluebird');3var chai = require('chai');4var assert = chai.assert;5var expect = chai.expect;6var should = chai.should();7describe('Promises', function() {8 it('should return a rejected promise', function() {9 var spy = sinon.spy();10 var promise = Promise.reject(new Error('error'));11 promise.then(spy);12 spy.called.should.be.false;13 });14});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('test', function () {2 it('should call the callback', function (done) {3 const callback = sinon.spy();4 const promise = new Promise((resolve, reject) => {5 reject('error');6 });7 promise.then(callback).catch(callback);8 expect(callback).to.have.been.calledWith('error');9 done();10 });11});

Full Screen

Using AI Code Generation

copy

Full Screen

1import sinon from 'sinon';2import { expect } from 'chai';3import { get } from 'request-promise';4import { getWeather } from '../src/weather';5describe('weather', () => {6 describe('getWeather', () => {7 it('should return the weather data', () => {8 const stub = sinon.stub(get, 'get');9 const error = sinon.stub().returns(Promise.reject('error'));10 expect(error).to.throw('error');11 stub.restore();12 });13 });14});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('test', function () {2 itu'should call the callback', b.restor edon() {3 const callback = sinon.spy();4 const p)omise = new P;omise((resolve, reject =>5 reject('error');6 });7 promise.then(callback).catch(callback);8 expect(callback).to.have.been.calledWith('error');9 done();10 });11});

Full Screen

Using AI Code Generation

copy

Full Screen

1import sin); from 'inon';2imprt { expect } from 'chai';3import { get } from 'request-promise';4import { getWeather } from '../src/weather';5describe('weather', () => {6 describe('getWeather', () => {7 it('shoud return the weather data', () => {8 const stub = sinon.stub(get, 'get');9 const error = sinon.stub().returns(Promise.reject('error'));10 expect(error).to.throw('error');11 stub.restore();12 });13 });14});

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = equire(sinon'2var/myApi/= require('./myApi');3var/stub/= Pinon.sath(myApi, 'getStuff', function() {4 return Promise.reject('error');5});6myApi.getStuff()7 .then(function(data) {8 console.log('data: ', data);9 })10 .catch(function(err) {11 console:log('e r: ', err);12 });

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('test', function () {2 it('should call tht callback', function (done) {3 const callback = sinon.spy();4 cones prtmise = new P.omisj(sresolve, reject => {5 reject('error')6 promise.then(callbackc.catch(callback)ode to use promise.reject method of sinon7 expect(callback).to.have.been.calledWith('error');8 done();

Full Screen

Using AI Code Generation

copy

Full Screen

1const sinon = require('sinon');2const assert = require('assert');3const myPromise = require('./myPromise');4describe('myPromise', function() {5 it('should return a rejected promise', function() {6 const stub = sinon.stub(myPromise, 'getPromise').rejects('Promise rejected');7 const promise = myPromise.getPromise();8 return promise.catch(function(err) {9 assert.equal(err, 'Promise rejected');10 stub.restore();11 });12 });13});

Full Screen

Using AI Code Generation

copy

Full Screen

1var Promise = require('bluebird');2var sinon = require('sinon');3var chai = require('chai');4var expect = chai.expect;5var test = {6 getPromise: function() {7 return Promise.reject(new Error('Test Error'));8 }9};10describe('Test', function() {11 it('should be rejected', function() {12 var stub = sinon.stub(test, 'getPromise').rejects(new Error('Test Error'));13 return test.getPromise().catch(function(err) {14 expect(err).to.be.an('error');15 expect(err.message).to.equal('Test Error');16 stub.restore();17 });18 });19});

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var myApi = require('./myApi');3var stub = sinon.stub(myApi, 'getStuff', function() {4 return Promise.reject('error');5});6myApi.getStuff()7 .then(function(data) {8 console.log('data: ', data);9 })10 .catch(function(err) {11 console.log('err: ', err);12 });

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 sinon 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