Best JavaScript code snippet using sinon
utilities.test.js
Source:utilities.test.js
...121 });122 describe('query rejects', () => {123 it('bubbles error @unit', async () => {124 const error = Error();125 const query = sinon.fake.rejects(error);126 const model = { findByPk: query };127 const { strictFindByKey } = proxyquire(REQUIRE_PATH, {128 './utilities.js': {129 createOrKeepTransaction: ignore,130 rollbackOrKeepTransaction: ignore,131 },132 });133 await assert.isRejected(strictFindByKey(model), error);134 });135 it('rolls back transaction @unit', async () => {136 const query = sinon.fake.rejects();137 const rollback = sinon.fake.resolves();138 const model = { findByPk: query };139 const { strictFindByKey } = proxyquire(REQUIRE_PATH, {140 './utilities.js': {141 createOrKeepTransaction: ignore,142 rollbackOrKeepTransaction: rollback,143 },144 });145 try {146 await strictFindByKey(model);147 } catch {} // eslint-disable-line no-empty148 assert.ok(rollback.called);149 });150 });151 });152 describe('update by key', () => {153 describe('find resolves', () => {154 describe('update resolves', () => {155 it('commits transaction @unit', async () => {156 const commit = sinon.fake();157 const instance = () => ({ update: ignore });158 const model = { strictFindByKey: instance };159 const { updateByKey } = proxyquire(REQUIRE_PATH, {160 './utilities.js': {161 createOrKeepTransaction: ignore,162 commitOrKeepTransaction: commit,163 },164 });165 await updateByKey(model);166 assert.ok(commit.called);167 });168 it('returns the updated item @unit', async () => {169 const expected = {};170 const instance = () => ({ update: () => expected });171 const model = { strictFindByKey: instance };172 const { updateByKey } = proxyquire(REQUIRE_PATH, {173 './utilities.js': {174 createOrKeepTransaction: ignore,175 commitOrKeepTransaction: ignore,176 },177 });178 const result = await updateByKey(model);179 assert.strictEqual(result, expected);180 });181 });182 describe('update rejects', () => {183 it('rolls back transaction @unit', async () => {184 const instance = () => ({ update: sinon.fake.rejects() });185 const rollback = sinon.fake();186 const model = { strictFindByKey: instance };187 const { updateByKey } = proxyquire(REQUIRE_PATH, {188 './utilities.js': {189 createOrKeepTransaction: ignore,190 rollbackOrKeepTransaction: rollback,191 },192 });193 try {194 await updateByKey(model);195 } catch {} // eslint-disable-line no-empty196 assert.ok(rollback.called);197 });198 it('bubbles error @unit', async () => {199 const error = Error();200 const instance = () => ({201 update: sinon.fake.rejects(error),202 });203 const model = { strictFindByKey: instance };204 const { updateByKey } = proxyquire(REQUIRE_PATH, {205 './utilities.js': {206 createOrKeepTransaction: ignore,207 rollbackOrKeepTransaction: ignore,208 },209 });210 await assert.isRejected(updateByKey(model), error);211 });212 });213 });214 describe('find rejects', () => {215 it('rolls back transaction @unit', async () => {216 const rollback = sinon.fake();217 const rejects = sinon.fake.rejects();218 const model = { strictFindByKey: rejects };219 const { updateByKey } = proxyquire(REQUIRE_PATH, {220 './utilities.js': {221 createOrKeepTransaction: ignore,222 rollbackOrKeepTransaction: rollback,223 },224 });225 try {226 await updateByKey(model);227 } catch {} // eslint-disable-line no-empty228 assert.ok(rollback.called);229 });230 it('bubbles error @unit', async () => {231 const error = Error();232 const rejects = sinon.fake.rejects(error);233 const model = { strictFindByKey: rejects };234 const { updateByKey } = proxyquire(REQUIRE_PATH, {235 './utilities.js': {236 createOrKeepTransaction: ignore,237 rollbackOrKeepTransaction: ignore,238 },239 });240 await assert.isRejected(updateByKey(model), error);241 });242 });243 });244 describe('delete by key', () => {245 describe('find resolves', () => {246 describe('destroy resolves', () => {247 it('commits transaction @unit', async () => {248 const commit = sinon.fake();249 const instance = () => ({ destroy: ignore });250 const model = { strictFindByKey: instance };251 const { deleteByKey } = proxyquire(REQUIRE_PATH, {252 './utilities.js': {253 createOrKeepTransaction: ignore,254 commitOrKeepTransaction: commit,255 },256 });257 await deleteByKey(model);258 assert.ok(commit.called);259 });260 it('returns destroyed item @unit', async () => {261 const expected = {};262 const instance = () => ({ destroy: () => expected });263 const model = { strictFindByKey: instance };264 const { deleteByKey } = proxyquire(REQUIRE_PATH, {265 './utilities.js': {266 createOrKeepTransaction: ignore,267 commitOrKeepTransaction: ignore,268 },269 });270 const result = await deleteByKey(model);271 assert.strictEqual(result, expected);272 });273 });274 describe('destroy rejects', () => {275 it('rolls back transaction @unit', async () => {276 const instance = () => ({ destroy: sinon.fake.rejects() });277 const rollback = sinon.fake();278 const model = { strictFindByKey: instance };279 const { deleteByKey } = proxyquire(REQUIRE_PATH, {280 './utilities.js': {281 createOrKeepTransaction: ignore,282 rollbackOrKeepTransaction: rollback,283 },284 });285 try {286 await deleteByKey(model);287 } catch {} // eslint-disable-line no-empty288 assert.ok(rollback.called);289 });290 it('bubbles error @unit', async () => {291 const error = Error();292 const instance = () => ({293 destroy: sinon.fake.rejects(error),294 });295 const model = { strictFindByKey: instance };296 const { deleteByKey } = proxyquire(REQUIRE_PATH, {297 './utilities.js': {298 createOrKeepTransaction: ignore,299 rollbackOrKeepTransaction: ignore,300 },301 });302 await assert.isRejected(deleteByKey(model), error);303 });304 });305 });306 describe('find rejects', () => {307 it('rolls back transaction @unit', async () => {308 const rollback = sinon.fake();309 const rejects = sinon.fake.rejects();310 const model = { strictFindByKey: rejects };311 const { deleteByKey } = proxyquire(REQUIRE_PATH, {312 './utilities.js': {313 createOrKeepTransaction: ignore,314 rollbackOrKeepTransaction: rollback,315 },316 });317 try {318 await deleteByKey(model);319 } catch {} // eslint-disable-line no-empty320 assert.ok(rollback.called);321 });322 it('bubbles error @unit', async () => {323 const error = Error();324 const rejects = sinon.fake.rejects(error);325 const model = { strictFindByKey: rejects };326 const { deleteByKey } = proxyquire(REQUIRE_PATH, {327 './utilities.js': {328 createOrKeepTransaction: ignore,329 rollbackOrKeepTransaction: ignore,330 },331 });332 await assert.isRejected(deleteByKey(model), error);333 });334 });335 });...
mpesa.test.js
Source:mpesa.test.js
...51 it('should throw an error if parameters are invalid', () => {52 sinon.replace(53 logic,54 'mpesaExpressRequest',55 sinon.fake.rejects('Bad Request')56 );57 return expect(58 mpesa.mpesaExpressRequest(59 100,60 254712345678,61 123456,62 'passkey',63 'CustomerPayBillOnline',64 'reference',65 'description',66 'http://callbackurl.com'67 )68 ).to.eventually.be.rejectedWith('Bad Request');69 });70 });71 describe('mpesaExpressQuery()', () => {72 afterEach(() => {73 sinon.restore();74 });75 it('should return a successful response', () => {76 sinon.replace(77 logic,78 'mpesaExpressQuery',79 sinon.fake.resolves({80 resultCode: '1032',81 resultDescription: '[STK_CB - ]Request cancelled by user'82 })83 );84 return expect(mpesa.mpesaExpressQuery()).to.eventually.deep.equal({85 resultCode: '1032',86 resultDescription: '[STK_CB - ]Request cancelled by user'87 });88 });89 it('should throw an error if parameters are invalid', () => {90 sinon.replace(91 logic,92 'mpesaExpressQuery',93 sinon.fake.rejects('Bad Request')94 );95 return expect(mpesa.mpesaExpressQuery()).to.eventually.be.rejectedWith(96 'Bad Request'97 );98 });99 });100 describe('c2bRegisterUrl()', () => {101 afterEach(() => {102 sinon.restore();103 });104 it('should return a successful response', () => {105 sinon.replace(106 logic,107 'c2bRegisterUrl',108 sinon.fake.resolves({ responseDescription: 'success' })109 );110 return expect(111 mpesa.c2bRegisterUrl(112 'http://validationurl.com',113 'http://confirmationurl.com',114 'Completed'115 )116 ).to.eventually.deep.equal({117 responseDescription: 'success'118 });119 });120 it('should throw an error if parameters are invalid', () => {121 sinon.replace(logic, 'c2bRegisterUrl', sinon.fake.rejects('Bad Request'));122 return expect(123 mpesa.c2bRegisterUrl(124 'http://validationurl.com',125 'http://confirmationurl.com',126 'Completed'127 )128 ).to.eventually.be.rejectedWith('Bad Request');129 });130 });131 describe('c2bSimulateTransaction()', () => {132 afterEach(() => {133 sinon.restore();134 });135 it('should return a successful response', () => {136 sinon.replace(137 logic,138 'c2bSimulateTransaction',139 sinon.fake.resolves({140 conversationId: 'conversationId',141 originatorConversationId: 'originatorConversationId',142 responseDescription: 'Accept the service request successfully.'143 })144 );145 return expect(146 mpesa.c2bSimulateTransaction(100, 254712345678, 'billRef')147 ).to.eventually.deep.equal({148 conversationId: 'conversationId',149 originatorConversationId: 'originatorConversationId',150 responseDescription: 'Accept the service request successfully.'151 });152 });153 it('should throw an error if parameters are invalid', () => {154 sinon.replace(155 logic,156 'c2bSimulateTransaction',157 sinon.fake.rejects('Bad Request')158 );159 return expect(160 mpesa.c2bSimulateTransaction(100, 254712345678, 'billRef')161 ).to.eventually.be.rejectedWith('Bad Request');162 });163 });164 describe('b2cPaymentRequest()', () => {165 afterEach(() => {166 sinon.restore();167 });168 it('should return a successful response', () => {169 sinon.replace(170 logic,171 'b2cPaymentRequest',172 sinon.fake.resolves({173 conversationId: 'conversationId',174 originatorConversationId: 'originatorConversationId',175 responseDescription: 'Accept the service request successfully.'176 })177 );178 return expect(179 mpesa.b2cPaymentRequest(100, 254712345678, 'billRef')180 ).to.eventually.deep.equal({181 conversationId: 'conversationId',182 originatorConversationId: 'originatorConversationId',183 responseDescription: 'Accept the service request successfully.'184 });185 });186 it('should throw an error if parameters are invalid', () => {187 sinon.replace(188 logic,189 'b2cPaymentRequest',190 sinon.fake.rejects('Bad Request')191 );192 return expect(193 mpesa.b2cPaymentRequest(100, 254712345678, 'billRef')194 ).to.eventually.be.rejectedWith('Bad Request');195 });196 });197 describe('accountBalanceRequest()', () => {198 afterEach(() => {199 sinon.restore();200 });201 it('should return a successful response', () => {202 sinon.replace(203 logic,204 'accountBalanceRequest',205 sinon.fake.resolves({206 conversationId: 'conversationId',207 originatorConversationId: 'originatorConversationId',208 responseDescription: 'Accept the service request successfully.'209 })210 );211 return expect(212 mpesa.accountBalanceRequest(100, 254712345678, 'billRef')213 ).to.eventually.deep.equal({214 conversationId: 'conversationId',215 originatorConversationId: 'originatorConversationId',216 responseDescription: 'Accept the service request successfully.'217 });218 });219 it('should throw an error if parameters are invalid', () => {220 sinon.replace(221 logic,222 'accountBalanceRequest',223 sinon.fake.rejects('Bad Request')224 );225 return expect(226 mpesa.accountBalanceRequest(100, 254712345678, 'billRef')227 ).to.eventually.be.rejectedWith('Bad Request');228 });229 });230 describe('transactionStatusRequest()', () => {231 afterEach(() => {232 sinon.restore();233 });234 it('should return a successful response', () => {235 sinon.replace(236 logic,237 'transactionStatusRequest',238 sinon.fake.resolves({239 conversationId: 'conversationId',240 originatorConversationId: 'originatorConversationId',241 responseDescription: 'Accept the service request successfully.'242 })243 );244 return expect(245 mpesa.transactionStatusRequest(246 'transactionId',247 4,248 'initiatorName',249 'initiatorPassword',250 'remarks',251 'occassion',252 'http://resulturl.com',253 'http://timeouturl.com'254 )255 ).to.eventually.deep.equal({256 conversationId: 'conversationId',257 originatorConversationId: 'originatorConversationId',258 responseDescription: 'Accept the service request successfully.'259 });260 });261 it('should throw an error if parameters are invalid', () => {262 sinon.replace(263 logic,264 'transactionStatusRequest',265 sinon.fake.rejects('Bad Request')266 );267 return expect(268 mpesa.transactionStatusRequest(269 'transactionId',270 4,271 'initiatorName',272 'initiatorPassword',273 'remarks',274 'occassion',275 'http://resulturl.com',276 'http://timeouturl.com'277 )278 ).to.eventually.be.rejectedWith('Bad Request');279 });280 });281 describe('reversalRequest()', () => {282 afterEach(() => {283 sinon.restore();284 });285 it('should return a successful response', () => {286 sinon.replace(287 logic,288 'reversalRequest',289 sinon.fake.resolves({290 conversationId: 'conversationId',291 originatorConversationId: 'originatorConversationId',292 responseDescription: 'Accept the service request successfully.'293 })294 );295 return expect(296 mpesa.reversalRequest(297 'transactionId',298 'initiatorName',299 'initiatorPassword',300 'remarks',301 'occassion',302 'http://resulturl.com',303 'http://timeouturl.com'304 )305 ).to.eventually.deep.equal({306 conversationId: 'conversationId',307 originatorConversationId: 'originatorConversationId',308 responseDescription: 'Accept the service request successfully.'309 });310 });311 it('should throw an error if parameters are invalid', () => {312 sinon.replace(313 logic,314 'reversalRequest',315 sinon.fake.rejects('Bad Request')316 );317 return expect(318 mpesa.reversalRequest(319 'transactionId',320 'initiatorName',321 'initiatorPassword',322 'remarks',323 'occassion',324 'http://resulturl.com',325 'http://timeouturl.com'326 )327 ).to.eventually.be.rejectedWith('Bad Request');328 });329 });...
migrationSpec.mjs.js
Source:migrationSpec.mjs.js
...48 account3: {49 "dkim.enable": 1,50 },51 }),52 getDkimKeys: sinon.fake.rejects("not available"),53 getSignRulesUser: sinon.fake.rejects("not available"),54 };55 await migratePrefs();56 expect(prefs["arh.read"]).to.be.equal(true);57 expect(prefs["dkim.enable"]).to.be.equal(false);58 expect(prefs["dns.nameserver"]).to.be.equal("1.1.1.1");59 expect(prefs["key.storing"]).to.be.equal(2);60 expect(prefs.saveResult).to.be.equal(true);61 // renamed62 expect(prefs["policy.signRules.autoAddRule.enable"]).to.be.equal(true);63 expect(prefs["policy.signRules.error.wrong_sdid.asWarning"]).to.be.equal(true);64 // type changed65 expect(prefs["dns.proxy.port"]).to.be.equal(42);66 expect(prefs["account.dkim.enable"]("account1")).to.be.equal(false);67 expect(prefs["account.arh.read"]("account1")).to.be.equal(false);68 expect(prefs["account.arh.allowedAuthserv"]("account1")).to.be.equal("foo.com");69 expect(prefs["account.dkim.enable"]("account3")).to.be.equal(true);70 expect(prefs["account.arh.read"]("account3")).to.be.equal(true);71 expect(prefs["account.arh.allowedAuthserv"]("account3")).to.be.equal("");72 });73 it("errors should be ignored", async function () {74 browser.migration = {75 getUserPrefs: sinon.fake.resolves({76 "arh.read": true,77 "dkim.enable": "this should be a boolean",78 "dns.nameserver": "1.1.1.1",79 "this.pref.does.not.exist": "foo",80 "key.storing": 2,81 }),82 getDkimKeys: sinon.fake.rejects("not available"),83 getAccountPrefs: sinon.fake.resolves({84 account1: {85 "dkim.enable": true,86 "arh.read": false,87 "arh.allowedAuthserv": 1,88 },89 account3: {90 "dkim.enable": 2,91 },92 }),93 getSignRulesUser: sinon.fake.rejects("not available"),94 };95 await migratePrefs();96 expect(prefs["arh.read"]).to.be.equal(true);97 expect(prefs["dns.nameserver"]).to.be.equal("1.1.1.1");98 expect(prefs["key.storing"]).to.be.equal(2);99 // prefs with wrong type should have default value100 expect(prefs["dkim.enable"]).to.be.equal(true);101 expect(prefs["account.dkim.enable"]("account1")).to.be.equal(true);102 expect(prefs["account.arh.read"]("account1")).to.be.equal(true);103 expect(prefs["account.arh.allowedAuthserv"]("account1")).to.be.equal("");104 expect(prefs["account.dkim.enable"]("account3")).to.be.equal(false);105 });106 it("skip migration if preferences already exist", async function () {107 browser.migration = {108 getUserPrefs: sinon.fake.resolves({109 "arh.read": true,110 }),111 getAccountPrefs: sinon.fake.resolves({112 account1: {113 "arh.allowedAuthserv": "foo.com",114 },115 }),116 getDkimKeys: sinon.fake.rejects("not available"),117 getSignRulesUser: sinon.fake.rejects("not available"),118 };119 await prefs.setValue("dkim.enable", true);120 await migratePrefs();121 expect(prefs["arh.read"]).to.be.equal(false);122 expect(prefs["account.arh.allowedAuthserv"]("account1")).to.be.equal("");123 });124 it("don't skip migration if only sign rules exist", async function () {125 browser.migration = {126 getUserPrefs: sinon.fake.resolves({127 "arh.read": true,128 }),129 getAccountPrefs: sinon.fake.resolves({130 account1: {131 "arh.allowedAuthserv": "foo.com",132 },133 }),134 getDkimKeys: sinon.fake.rejects("not available"),135 getSignRulesUser: sinon.fake.rejects("not available"),136 };137 await SignRules.addException("foo@bar.com");138 await migratePrefs();139 expect(prefs["arh.read"]).to.be.equal(true);140 expect(prefs["account.arh.allowedAuthserv"]("account1")).to.be.equal("foo.com");141 });142 });143 describe("migration of keys", function () {144 before(function () {145 if (!hasWebExtensions) {146 // eslint-disable-next-line no-invalid-this147 this.skip();148 }149 });150 beforeEach(async function () {151 await KeyDb.clear();152 browser.migration = {153 getUserPrefs: sinon.fake.rejects("not available"),154 getAccountPrefs: sinon.fake.rejects("not available"),155 getDkimKeys: sinon.fake.resolves({156 maxId: 1,157 keys: [158 {159 id: 1,160 sdid: "foo.com",161 selector: "selector",162 key: "key",163 insertedAt: "2021-02-03",164 lastUsedAt: "2021-02-03",165 secure: false,166 },167 ],168 }),169 getSignRulesUser: sinon.fake.rejects("not available"),170 };171 });172 it("normal migration of keys", async function () {173 await migrateKeyStore();174 const res = await KeyDb.fetch("foo.com", "selector");175 expect(res?.key).is.equal("key");176 });177 it("skip migration if keys already exist", async function () {178 await KeyDb.store("bar.com", "selector", "key2", false);179 await migrateKeyStore();180 const res = await KeyDb.fetch("foo.com", "selector");181 expect(res).is.null;182 });183 it("don't skip migration of keys if only preferences exist", async function () {184 await prefs.setValue("dkim.enable", true);185 await migrateKeyStore();186 const res = await KeyDb.fetch("foo.com", "selector");187 expect(res?.key).is.equal("key");188 });189 });190 describe("migration of sign rules", function () {191 before(function () {192 if (!hasWebExtensions) {193 // eslint-disable-next-line no-invalid-this194 this.skip();195 }196 });197 beforeEach(async function () {198 await SignRules.clearRules();199 browser.migration = {200 getUserPrefs: sinon.fake.rejects("not available"),201 getAccountPrefs: sinon.fake.rejects("not available"),202 getDkimKeys: sinon.fake.rejects("not available"),203 getSignRulesUser: sinon.fake.resolves({204 maxId: 1,205 rules: [206 {207 id: 1,208 domain: "foo.com",209 listId: "",210 addr: "*",211 sdid: "foo.com",212 type: SignRules.TYPE.ALL,213 priority: SignRules.PRIORITY.USERINSERT_RULE_ALL,214 enabled: true,215 },216 ],...
Using AI Code Generation
1const sinon = require("sinon");2const chai = require("chai");3const expect = chai.expect;4const chaiAsPromised = require("chai-as-promised");5const sinonChai = require("sinon-chai");6chai.use(chaiAsPromised);7chai.use(sinonChai);8const fake = sinon.fake.rejects("error");9fake()10 .then((data) => {11 console.log("data", data);12 })13 .catch((err) => {14 console.log("err", err);15 });16const sinon = require("sinon");17const chai = require("chai");18const expect = chai.expect;19const chaiAsPromised = require("chai-as-promised");20const sinonChai = require("sinon-chai");21chai.use(chaiAsPromised);22chai.use(sinonChai);23const fake = sinon.fake.resolves("data");24fake()25 .then((data) => {26 console.log("data", data);27 })28 .catch((err) => {29 console.log("err", err);30 });31const sinon = require("sinon");32const chai = require("chai");33const expect = chai.expect;34const chaiAsPromised = require("chai-as-promised");35const sinonChai = require("sinon-chai");36chai.use(chaiAsPromised);37chai.use(sinonChai);38const fake = sinon.fake.yields("error", "data");39fake((err, data) => {40 console.log("err", err);41 console.log("data", data);42});
Using AI Code Generation
1const sinon = require('sinon');2const chai = require('chai');3const sinonChai = require('sinon-chai');4const expect = chai.expect;5chai.use(sinonChai);6describe('sinon fake rejects', () => {7 it('should fake a promise rejection', () => {8 const fake = sinon.fake.rejects(new Error('fake error'));9 return fake().catch((err) => {10 expect(err).to.exist;11 expect(err.message).to.equal('fake error');12 });13 });14});15- `sinon.useFakeTimers([now, toFake])`16- `clock.tick(ms)`17- `clock.runAll()`18- `clock.runToLast()`19- `clock.restore()`20const sinon = require('sinon');21const chai = require('chai');22const sinonChai = require('sinon-chai');23const expect = chai.expect;24chai.use(sinonChai);25describe('sinon fake timers', () => {26 it('should fake a timer', () => {27 const clock = sinon.useFakeTimers();28 const callback = sinon.fake();29 setTimeout(callback, 1000);30 expect(callback).to.not.have.been.called;31 clock.tick(1000);32 expect(callback).to.have.been.called;33 clock.restore();34 });35});36- `sinon.useFakeServer()`37- `server.respondWith([status, headers, body])`38- `server.respond()`39- `server.restore()`40const sinon = require('sinon');41const chai = require('chai');42const sinonChai = require('sinon-chai');43const expect = chai.expect;44chai.use(sinonChai);45describe('sinon fake server', () => {46 it('should fake a server', () => {47 const server = sinon.useFakeServer();48 const callback = sinon.fake();49 const xhr = new XMLHttpRequest();50 xhr.addEventListener('load
Using AI Code Generation
1const sinon = require('sinon');2const assert = require('assert');3const fake = sinon.fake.rejects(new Error('fake error'));4fake().catch(error => {5 assert(error.message === 'fake error');6});7const sinon = require('sinon');8const assert = require('assert');9const fake = sinon.fake.rejects(new Error('fake error'));10fake().catch(error => {11 assert(error.message === 'fake error');12});13const sinon = require('sinon');14const assert = require('assert');15const fake = sinon.fake.rejects(new Error('fake error'));16fake().catch(error => {17 assert(error.message === 'fake error');18});19const sinon = require('sinon');20const assert = require('assert');21const fake = sinon.fake.rejects(new Error('fake error'));22fake().catch(error => {23 assert(error.message === 'fake error');24});25const sinon = require('sinon');26const assert = require('assert');27const fake = sinon.fake.rejects(new Error('fake error'));28fake().catch(error => {29 assert(error.message === 'fake error');30});31const sinon = require('sinon');32const assert = require('assert');33const fake = sinon.fake.rejects(new Error('fake error'));34fake().catch(error => {35 assert(error.message === 'fake error');36});37const sinon = require('sinon');38const assert = require('assert');39const fake = sinon.fake.rejects(new Error('fake error'));40fake().catch(error => {41 assert(error.message === 'fake error');42});43const sinon = require('sinon');44const assert = require('assert');45const fake = sinon.fake.rejects(new Error('fake error'));46fake().catch(error => {47 assert(error.message === 'fake error');48});49const sinon = require('sinon');
Using AI Code Generation
1const sinon = require('sinon');2const assert = require('assert');3const { fake } = require('sinon');4const { rejects } = require('assert');5const myDatabase = {6 save: function (data, cb) {7 cb(null, true);8 },9 get: function (id, cb) {10 cb(null, { id: id });11 }12};13const myService = {14 save: function (data) {15 myDatabase.save(data, function (err, result) {16 if (err) {17 throw err;18 } else {19 console.log("Saved");20 }21 });22 },23 get: function (id) {24 myDatabase.get(id, function (err, result) {25 if (err) {26 throw err;27 } else {28 console.log("Got");29 }30 });31 }32};33describe('myService', function () {34 describe('#save()', function () {35 it('should save without error', function () {36 const callback = sinon.fake();37 myDatabase.save = sinon.fake.yields(null, true);38 myService.save({ id: 1 }, callback);39 assert(myDatabase.save.calledOnce);40 assert(callback.calledWith(null, true));41 });42 });43 describe('#get()', function () {44 it('should get without error', function () {45 const callback = sinon.fake();46 myDatabase.get = sinon.fake.yields(null, { id: 1 });47 myService.get(1, callback);48 assert(myDatabase.get.calledOnce);49 assert(callback.calledWith(null, { id: 1 }));50 });51 });52});53const sinon = require('sinon');54const assert = require('assert');55const { fake } = require('sinon');56const { rejects } = require('assert');57const myDatabase = {58 save: function (data, cb) {59 cb(null, true);60 },61 get: function (id, cb) {62 cb(null, { id: id });63 }64};65const myService = {66 save: function (data) {67 myDatabase.save(data, function (err, result) {68 if (err) {69 throw err;70 } else {71 console.log("Saved");72 }73 });74 },75 get: function (id) {76 myDatabase.get(id,
Using AI Code Generation
1var fake = require('sinon').fake;2var fakeRejects = fake.rejects('Error');3fakeRejects.then(function (result) {4 console.log(result);5}, function (error) {6 console.log(error);7});8var fake = require('sinon').fake;9var fakeResolves = fake.resolves('Success');10fakeResolves.then(function (result) {11 console.log(result);12}, function (error) {13 console.log(error);14});15var fake = require('sinon').fake;16var fakeYields = fake.yields('Error', 'Success');17fakeYields(function (error, result) {18 console.log(error, result);19});20var fake = require('sinon').fake;21var fakeYieldsTo = fake.yieldsTo('callback', 'Error', 'Success');22fakeYieldsTo({ callback: function (error, result) { console.log(error, result); } });23var fake = require('sinon').fake;24var fakeWithArgs = fake.withArgs(1, 2);25fakeWithArgs(1, 2);26fakeWithArgs(3, 4);27console.log(fakeWithArgs.callCount);28var fake = require('sinon').fake;29var fakeWithArgs = fake.withArgs(1, 2);30fakeWithArgs(1, 2);31fakeWithArgs(3, 4);32console.log(fakeWithArgs.callCount);33var fake = require('sinon').fake;34var fakeWithArgs = fake.withArgs(1, 2);35fakeWithArgs(1, 2);36fakeWithArgs(3, 4);37console.log(fakeWithArgs.callCount);38var fake = require('sinon').fake;39var fakeWithArgs = fake.withArgs(1, 2);40fakeWithArgs(1, 2);41fakeWithArgs(3, 4);
Using AI Code Generation
1const sinon = require('sinon');2const fake = sinon.fake.returns(Promise.reject(new Error('error')));3const fake2 = sinon.fake.returns(Promise.resolve('success'));4const test = async () => {5 try {6 const result = await fake();7 console.log(result);8 } catch (err) {9 console.log(err);10 }11};12const test2 = async () => {13 try {14 const result = await fake2();15 console.log(result);16 } catch (err) {17 console.log(err);18 }19};20test();21test2();
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!