How to use assert.rejects method in sinon

Best JavaScript code snippet using sinon

test-assert-async.js

Source:test-assert-async.js Github

copy

Full Screen

...20 };21 f.catch = () => {};22 return f;23};24// Test assert.rejects() and assert.doesNotReject() by checking their25// expected output and by verifying that they do not work sync26// Check `assert.rejects`.27{28 const rejectingFn = async () => assert.fail();29 const errObj = {30 code: 'ERR_ASSERTION',31 name: 'AssertionError',32 message: 'Failed'33 };34 // `assert.rejects` accepts a function or a promise35 // or a thenable as first argument.36 promises.push(assert.rejects(rejectingFn, errObj));37 promises.push(assert.rejects(rejectingFn(), errObj));38 const validRejectingThenable = {39 then: (fulfill, reject) => {40 reject({ code: 'FAIL' });41 },42 catch: () => {}43 };44 promises.push(assert.rejects(validRejectingThenable, { code: 'FAIL' }));45 // `assert.rejects` should not accept thenables that46 // use a function as `obj` and that have no `catch` handler.47 promises.push(assert.rejects(48 assert.rejects(invalidThenable, {}),49 {50 code: 'ERR_INVALID_ARG_TYPE'51 })52 );53 promises.push(assert.rejects(54 assert.rejects(invalidThenableFunc, {}),55 {56 code: 'ERR_INVALID_RETURN_VALUE'57 })58 );59 const err = new Error('foobar');60 const validate = () => { return 'baz'; };61 promises.push(assert.rejects(62 () => assert.rejects(Promise.reject(err), validate),63 {64 message: 'The "validate" validation function is expected to ' +65 "return \"true\". Received 'baz'\n\nCaught error:\n\n" +66 'Error: foobar',67 code: 'ERR_ASSERTION',68 actual: err,69 expected: validate,70 name: 'AssertionError',71 operator: 'rejects',72 }73 ));74}75{76 const handler = (err) => {77 assert(err instanceof assert.AssertionError,78 `${err.name} is not instance of AssertionError`);79 assert.strictEqual(err.code, 'ERR_ASSERTION');80 assert.strictEqual(err.message,81 'Missing expected rejection (mustNotCall).');82 assert.strictEqual(err.operator, 'rejects');83 assert.ok(!err.stack.includes('at Function.rejects'));84 return true;85 };86 let promise = assert.rejects(async () => {}, common.mustNotCall());87 promises.push(assert.rejects(promise, common.mustCall(handler)));88 promise = assert.rejects(() => {}, common.mustNotCall());89 promises.push(assert.rejects(promise, {90 name: 'TypeError',91 code: 'ERR_INVALID_RETURN_VALUE',92 message: 'Expected instance of Promise to be returned ' +93 'from the "promiseFn" function but got type undefined.'94 }));95 promise = assert.rejects(Promise.resolve(), common.mustNotCall());96 promises.push(assert.rejects(promise, common.mustCall(handler)));97}98{99 const THROWN_ERROR = new Error();100 promises.push(assert.rejects(() => {101 throw THROWN_ERROR;102 }, {}).catch(common.mustCall((err) => {103 assert.strictEqual(err, THROWN_ERROR);104 })));105}106promises.push(assert.rejects(107 assert.rejects('fail', {}),108 {109 code: 'ERR_INVALID_ARG_TYPE',110 message: 'The "promiseFn" argument must be of type function or an ' +111 "instance of Promise. Received type string ('fail')"112 }113));114{115 const handler = (generated, actual, err) => {116 assert.strictEqual(err.generatedMessage, generated);117 assert.strictEqual(err.code, 'ERR_ASSERTION');118 assert.strictEqual(err.actual, actual);119 assert.strictEqual(err.operator, 'rejects');120 assert(/rejects/.test(err.stack));121 return true;122 };123 const err = new Error();124 promises.push(assert.rejects(125 assert.rejects(Promise.reject(null), { code: 'FOO' }),126 handler.bind(null, true, null)127 ));128 promises.push(assert.rejects(129 assert.rejects(Promise.reject(5), { code: 'FOO' }, 'AAAAA'),130 handler.bind(null, false, 5)131 ));132 promises.push(assert.rejects(133 assert.rejects(Promise.reject(err), { code: 'FOO' }, 'AAAAA'),134 handler.bind(null, false, err)135 ));136}137// Check `assert.doesNotReject`.138{139 // `assert.doesNotReject` accepts a function or a promise140 // or a thenable as first argument.141 /* eslint-disable no-restricted-syntax */142 let promise = assert.doesNotReject(() => new Map(), common.mustNotCall());143 promises.push(assert.rejects(promise, {144 message: 'Expected instance of Promise to be returned ' +145 'from the "promiseFn" function but got instance of Map.',146 code: 'ERR_INVALID_RETURN_VALUE',147 name: 'TypeError'148 }));149 promises.push(assert.doesNotReject(async () => {}));150 promises.push(assert.doesNotReject(Promise.resolve()));151 // `assert.doesNotReject` should not accept thenables that152 // use a function as `obj` and that have no `catch` handler.153 const validFulfillingThenable = {154 then: (fulfill, reject) => {155 fulfill();156 },157 catch: () => {}158 };159 promises.push(assert.doesNotReject(validFulfillingThenable));160 promises.push(assert.rejects(161 assert.doesNotReject(invalidThenable),162 {163 code: 'ERR_INVALID_ARG_TYPE'164 })165 );166 promises.push(assert.rejects(167 assert.doesNotReject(invalidThenableFunc),168 {169 code: 'ERR_INVALID_RETURN_VALUE'170 })171 );172 const handler1 = (err) => {173 assert(err instanceof assert.AssertionError,174 `${err.name} is not instance of AssertionError`);175 assert.strictEqual(err.code, 'ERR_ASSERTION');176 assert.strictEqual(err.message, 'Failed');177 return true;178 };179 const handler2 = (err) => {180 assert(err instanceof assert.AssertionError,181 `${err.name} is not instance of AssertionError`);182 assert.strictEqual(err.code, 'ERR_ASSERTION');183 assert.strictEqual(err.message,184 'Got unwanted rejection.\nActual message: "Failed"');185 assert.strictEqual(err.operator, 'doesNotReject');186 assert.ok(err.stack);187 assert.ok(!err.stack.includes('at Function.doesNotReject'));188 return true;189 };190 const rejectingFn = async () => assert.fail();191 promise = assert.doesNotReject(rejectingFn, common.mustCall(handler1));192 promises.push(assert.rejects(promise, common.mustCall(handler2)));193 promise = assert.doesNotReject(rejectingFn(), common.mustCall(handler1));194 promises.push(assert.rejects(promise, common.mustCall(handler2)));195 promise = assert.doesNotReject(() => assert.fail(), common.mustNotCall());196 promises.push(assert.rejects(promise, common.mustCall(handler1)));197 promises.push(assert.rejects(198 assert.doesNotReject(123),199 {200 code: 'ERR_INVALID_ARG_TYPE',201 message: 'The "promiseFn" argument must be of type ' +202 'function or an instance of Promise. Received type number (123)'203 }204 ));205 /* eslint-enable no-restricted-syntax */206}207// Make sure all async code gets properly executed....

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const assert = require('assert');2const myModule = require('./myModule');3assert.rejects(4 async () => {5 await myModule();6 },7 {8 }9);10const sinon = require('sinon');11const myModule = require('./myModule');12sinon.stub(myModule, 'myModule').throws({ name: 'Error', message: 'Wrong value' });13myModule();14const sinon = require('sinon');15const myModule = require('./myModule');16sinon.mock(myModule).expects('myModule').throws({ name: 'Error', message: 'Wrong value' });17myModule();18const sinon = require('sinon');19const myModule = require('./myModule');20const mySpy = sinon.spy();21myModule(mySpy);22assert(mySpy.calledWith({ name: 'Error', message: 'Wrong value' }));23const sinon = require('sinon');24const myModule = require('./myModule');25const myFake = sinon.fake.throws({ name: 'Error', message: 'Wrong value' });26myModule(myFake);27assert(myFake.called);28const sinon = require('sinon');29const myModule = require('./myModule');30sinon.stub(myModule, 'myModule').throws({ name: 'Error', message: 'Wrong value' });31myModule();32const sinon = require('sinon');33const myModule = require('./myModule');34sinon.mock(myModule).expects('myModule').throws({ name: 'Error', message: 'Wrong value' });35myModule();36const sinon = require('sinon');37const myModule = require('./myModule');38const mySpy = sinon.spy();39myModule(mySpy);40assert(mySpy.calledWith({ name: 'Error', message: 'Wrong value' }));41const sinon = require('sinon');42const myModule = require('./myModule');43const myFake = sinon.fake.throws({ name: 'Error', message: 'Wrong value' });44myModule(myFake);45assert(myFake.called);46const sinon = require('sinon');

Full Screen

Using AI Code Generation

copy

Full Screen

1const assert = require('assert');2const sinon = require('sinon');3const { rejects } = require('assert');4const myAsyncFunction = () => {5 return new Promise((resolve, reject) => {6 setTimeout(() => {7 reject(new Error('Async Error'));8 }, 100);9 });10};11(async () => {12 try {13 await assert.rejects(14 myAsyncFunction(),15 new Error('Async Error')16 );17 }18 catch (error) {19 console.log(error);20 }21})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const assert = require('assert');2const sinon = require('sinon');3async function test() {4 const promise = Promise.reject(new Error('error'));5 await assert.rejects(6 );7 await assert.rejects(8 new Error('error'),9 );10 await assert.rejects(11 );12 await assert.rejects(13 sinon.match((value) => value.message === 'error'),14 );15 await assert.rejects(16 {17 },18 );19}20test();21### `assert.resolves(promise[, expected], [message])`22const assert = require('assert');23const sinon = require('sinon');24async function test() {25 const promise = Promise.resolve('ok');26 await assert.resolves(27 );28 await assert.resolves(29 );30 await assert.resolves(31 sinon.match((value) => value === 'ok'),32 );33}34test();35### `assert.called(spy)`36const assert = require('assert');37const sinon = require('sinon');38function test() {39 const spy = sinon.spy();40 spy('foo');41 assert.called(spy);42}43test();44### `assert.calledOnce(spy)`45const assert = require('assert');46const sinon = require('sinon');47function test() {48 const spy = sinon.spy();49 spy('foo');50 assert.calledOnce(s

Full Screen

Using AI Code Generation

copy

Full Screen

1const assert = require('assert');2const sinon = require('sinon');3const { throwError } = require('./throwError');4describe('throwError', () => {5 it('should throw an error', async () => {6 const error = new Error('error');7 const promise = throwError();8 assert.rejects(promise, error);9 });10});11const throwError = () => {12 return new Promise((resolve, reject) => {13 reject(new Error('error'));14 });15};16module.exports = { throwError };

Full Screen

Using AI Code Generation

copy

Full Screen

1const assert = require('assert');2const sinon = require('sinon');3const test = async () => {4 const promise = () => Promise.reject(new Error('promise rejected'));5 await assert.rejects(promise(), Error);6};7test();8const assert = require('assert');9const sinon = require('sinon');10const test = async () => {11 const promise = () => Promise.reject(new Error('promise rejected'));12 await sinon.assert.rejects(promise(), Error);13};14test();15const assert = require('assert');16const sinon = require('sinon');17const test = async () => {18 const promise = () => Promise.reject(new Error('promise rejected'));19 await sinon.assert.isRejected(promise(), Error);20};21test();22const assert = require('assert');23const sinon = require('sinon');24const test = async () => {25 const promise = () => Promise.reject(new Error('promise rejected'));26 await sinon.assert.isRejected(promise(), Error);27};28test();29const assert = require('assert');30const sinon = require('sinon');31const test = async () => {32 const promise = () => Promise.reject(new Error('promise rejected'));33 await sinon.assert.isRejected(promise(), Error);34};35test();

Full Screen

Using AI Code Generation

copy

Full Screen

1const sinon = require('sinon');2const assert = require('assert');3const { rejects } = require('assert');4const fetch = require('node-fetch');5describe('sinon', () => {6 it('should reject with an error', () => {7 const error = new Error('Not Found');8 const promise = fetch(url).then(response => {9 if (response.ok) {10 return response.json();11 }12 throw error;13 });14 return assert.rejects(promise, error);15 });16});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('test', function() {2 it('should return a promise', function() {3 return assert.rejects(Promise.reject('error'));4 });5});6describe('test', function() {7 it('should return a promise', function() {8 return sinon.assert.rejected(Promise.reject('error'));9 });10});

Full Screen

Using AI Code Generation

copy

Full Screen

1const assert = require('assert');2const myFunc = require('./myFunc');3describe('test myFunc', () => {4 it('should assert myFunc', async () => {5 const myFuncPromise = myFunc();6 await assert.rejects(myFuncPromise, {7 });8 });9});

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