How to use isAssertionError method in Jest

Best JavaScript code snippet using jest

error.spec.js

Source:error.spec.js Github

copy

Full Screen

...13 };14};15function doneOnError(done) {16 return function(e) {17 if (isAssertionError(e)) {18 return done(e);19 }20 return done();21 };22};23describe("Error", function() {24 it("should get a hard error from the DataSource with _treatDataSourceErrorsAsJSONGraphErrors.", function(done) {25 var model = new Model({26 source: new ErrorDataSource(503, "Timeout"),27 _treatDataSourceErrorsAsJSONGraphErrors: true28 });29 var onNext = jest.fn();30 toObservable(model.31 get(["test", {to: 5}, "summary"])).32 doAction(onNext, function(err) {33 expect(onNext).toHaveBeenCalledTimes(1);34 expect(clean(onNext.mock.calls[0][0])).toEqual({35 json: {36 test: {37 0: {},38 1: {},39 2: {},40 3: {},41 4: {},42 5: {}43 }44 }45 });46 expect(err.length).toBe(6);47 // not in boxValue mode48 var expected = {49 path: [],50 value: {51 status: 503,52 message: "Timeout"53 }54 };55 err.forEach(function(e, i) {56 expected.path = ["test", i, "summary"];57 expect(e).toEqual(expected);58 });59 }).60 subscribe(noOp,61 function(e) {62 if (isAssertionError(e)) {63 done(e);64 } else {65 done();66 }67 },68 function() {69 done('Should not onComplete');70 });71 });72 it("should get a hard error from the DataSource.", function(done) {73 var model = new Model({74 source: new ErrorDataSource(503, "Timeout")75 });76 toObservable(model.77 get(["test", {to: 5}, "summary"])).78 doAction(noOp, function(err) {79 // not in boxValue mode80 var expected = {81 $type: "error",82 value: {83 status: 503,84 message: "Timeout"85 }86 };87 expect(err).toEqual(expected);88 }).89 subscribe(noOp,90 function(e) {91 if (isAssertionError(e)) {92 done(e);93 } else {94 done();95 }96 },97 function() {98 done('Should not onComplete');99 });100 });101 it("should get a hard error from the DataSource with some data found in the cache with _treatDataSourceErrorsAsJSONGraphErrors.", function(done) {102 var model = new Model({103 _treatDataSourceErrorsAsJSONGraphErrors: true,104 source: new ErrorDataSource(503, "Timeout"),105 cache: {106 test: {107 0: {108 summary: "in cache"109 },110 5: {111 summary: "in cache"112 }113 }114 }115 });116 var onNext = jest.fn();117 toObservable(model.118 get(["test", {to: 5}, "summary"])).119 doAction(onNext, function(err) {120 // Ensure onNext is called correctly121 expect(onNext).toHaveBeenCalledTimes(1);122 expect(err.length).toBe(4);123 // not in boxValue mode124 var expected = {125 path: [],126 value: {127 status: 503,128 message: "Timeout"129 }130 };131 err.forEach(function(e, i) {132 expected.path = ["test", i + 1, "summary"];133 expect(e).toEqual(expected);134 });135 }).136 subscribe(noOp, doneOnError(done), errorOnCompleted(done));137 });138 it("should get a hard error from the DataSource with some data found in the cache.", function(done) {139 var model = new Model({140 source: new ErrorDataSource(503, "Timeout"),141 cache: {142 test: {143 0: {144 summary: "in cache"145 },146 5: {147 summary: "in cache"148 }149 }150 }151 });152 var onNext = jest.fn();153 toObservable(model.154 get(["test", {to: 5}, "summary"])).155 doAction(onNext, function(err) {156 expect(onNext).toHaveBeenCalledTimes(1);157 expect(clean(onNext.mock.calls[0][0])).toEqual({158 json: {159 test: {160 0: {161 summary: 'in cache'162 },163 5: {164 summary: 'in cache'165 }166 }167 }168 });169 // not in boxValue mode170 var expected = {171 $type: "error",172 value: {173 status: 503,174 message: "Timeout"175 }176 };177 expect(err).toEqual(expected);178 }).179 subscribe(noOp, doneOnError(done), errorOnCompleted(done));180 });181 it("should onNext when only receiving errors.", function(done) {182 var model = new Model({183 source: new Model({184 cache: {185 test: {186 0: {187 summary: {188 $type: 'error',189 value: {190 message: 'Oops!',191 status: 500192 }193 }194 },195 1: {196 summary: {197 $type: 'error',198 value: {199 message: 'Oops!',200 status: 500201 }202 }203 }204 }205 }206 }).asDataSource()207 });208 var onNext = jest.fn();209 toObservable(model.210 get(["test", {to: 1}, "summary"])).211 doAction(onNext, function(err) {212 expect(onNext).toHaveBeenCalledTimes(1);213 expect(clean(onNext.mock.calls[0][0])).toEqual({214 json: {215 test: {216 0: {},217 1: {}218 }219 }220 });221 // not in boxValue mode222 var expected = [223 {"path":["test",0,"summary"],"value":{"message":"Oops!","status":500}},224 {"path":["test",1,"summary"],"value":{"message":"Oops!","status":500}}225 ];226 expect(err).toEqual(expected);227 }).228 subscribe(noOp, doneOnError(done), errorOnCompleted(done));229 });230 it("should onNext when receiving errors and missing paths.", function(done) {231 var model = new Model({232 source: new Model({233 cache: {234 test: {235 0: {236 summary: {237 $type: 'error',238 value: {239 message: 'Oops!',240 status: 500241 }242 }243 },244 5: {245 summary: {246 $type: 'error',247 value: {248 message: 'Oops!',249 status: 500250 }251 }252 }253 }254 }255 }).asDataSource()256 });257 var onNext = jest.fn();258 toObservable(model.259 get(["test", {to: 5}, "summary"])).260 doAction(onNext, function(err) {261 expect(onNext).toHaveBeenCalledTimes(1);262 expect(clean(onNext.mock.calls[0][0]), 'json from onNext').toEqual({263 json: {264 test: {265 0: {},266 5: {}267 }268 }269 });270 // not in boxValue mode271 var expected = [272 {"path":["test",0,"summary"],"value":{"message":"Oops!","status":500}},273 {"path":["test",5,"summary"],"value":{"message":"Oops!","status":500}}274 ];275 expect(err).toEqual(expected);276 }).277 subscribe(noOp, doneOnError(done), errorOnCompleted(done));278 });279 it('should allow for dataSources to immediately throw an error (set)', function(done) {280 var routes = {281 set: function() {282 return thisVarDoesNotExistAndThatsAFact;283 }284 };285 var model = new falcor.Model({ source: routes });286 var onNext = jest.fn();287 var onError = jest.fn();288 toObservable(model.289 set({290 paths: [['titlesById', 242, 'rating']],291 jsonGraph: {292 titlesById: {293 242: {294 rating: 5295 }296 }297 }298 })).299 doAction(onNext, onError).300 doAction(noOp, function() {301 expect(onNext).not.toHaveBeenCalled();302 expect(onError).toHaveBeenCalledTimes(1);303 expect(onError.mock.calls[0][0].name).toBe(InvalidSourceError.name);304 }).305 subscribe(noOp, function(e) {306 if (isAssertionError(e)) {307 return done(e);308 }309 return done();310 }, done.bind(null, new Error('should not complete')));311 });312 it('should allow for dataSources to immediately throw an error (get)', function(done) {313 var routes = {314 get: function() {315 return thisVarDoesNotExistAndThatsAFact;316 }317 };318 var model = new falcor.Model({ source: routes });319 var onNext = jest.fn();320 var onError = jest.fn();321 toObservable(model.322 get(['path', 'to', 'value'])).323 doAction(onNext, function(e) {324 expect(onNext).toHaveBeenCalledTimes(1);325 expect(clean(onNext.mock.calls[0][0])).toEqual({326 json: {327 }328 })329 expect(e.name).toBe(InvalidSourceError.name);330 }).331 subscribe(noOp, function(e) {332 if (isAssertionError(e)) {333 return done(e);334 }335 return done();336 }, done.bind(null, new Error('should not complete')));337 });338 it('should allow for dataSources to immediately throw an error (call)', function(done) {339 var routes = {340 call: function() {341 return thisVarDoesNotExistAndThatsAFact;342 }343 };344 var model = new falcor.Model({ source: routes });345 var onNext = jest.fn();346 toObservable(model.347 call(['videos', 1234, 'rating'], 5)).348 doAction(onNext).349 doAction(noOp, function(err) {350 expect(onNext).not.toHaveBeenCalled();351 expect(err.name).toBe(InvalidSourceError.name);352 }).353 subscribe(noOp, function(e) {354 if (isAssertionError(e)) {355 return done(e);356 }357 return done();358 }, done.bind(null, new Error('should not complete')));359 });...

Full Screen

Full Screen

socketChainHelper.js

Source:socketChainHelper.js Github

copy

Full Screen

1const fs = require('fs');2const path = require('path');3const {isNil} = require('ramda');4const assert = require('assert');5const SuitestError = require('./SuitestError');6const {7 getErrorMessage,8 getInfoErrorMessage,9 normalizeErrorType,10 responseMessageCode,11} = require('./socketErrorMessages');12const t = require('../texts');13const {mapLogLevelsToTranslationModule} = require('./chainUtils');14const {getSnippetLogs} = require('./socketErrorMessages');15const assertionErrorTypes = ['queryFailed', 'appRunning', 'appNotRunning', 'queryTimeout'];16/**17 * Process network api websocket chain response18 * @param logger19 * @param {verbosity} verbosity level20 * @returns {any}21 */22const processServerResponse = (logger, verbosity) =>23 function processServerResponseHandler(res, data, jsonMessage, snippets) {24 const isSnippet = data.type === 'runSnippet';25 const isAssertionError = isSnippet || assertionErrorTypes.includes(normalizeErrorType(res));26 const responseForError = getResponseForError(res);27 const message = getErrorMessage({28 response: res,29 verbosity,30 jsonMessage,31 snippets,32 });33 const throwErr = err => {34 err.stack = data.stack;35 throw err;36 };37 const infoMessage = prefix => getInfoErrorMessage(message, prefix, res, data.stack);38 const isSuccess = res.result === 'success' || res.result === 'warning';39 const isEval = res.contentType === 'eval';40 const isTestLine = res.contentType === 'testLine';41 const isQuery = res.contentType === 'query';42 const isTakeScreenshot = res.contentType === 'takeScreenshot';43 const isAborted = res.result === 'aborted';44 // warnings45 if (res.result === 'warning') {46 logger.warn(infoMessage(''));47 }48 // fatal errors49 if (res.result === 'fatal') {50 logger.error(infoMessage(''));51 throwErr(new SuitestError(message, SuitestError.UNKNOWN_ERROR, responseForError));52 }53 if (isAborted) {54 logger.error(t.executionAborted());55 throwErr(new SuitestError(t.executionAborted()));56 }57 // query58 if (isQuery) {59 // if one of query fields is on res, return it60 const queryKeyFound = [61 'cookieValue',62 'cookieExists',63 'elementProps',64 'elementCssProps',65 'elementExists',66 'elementHandles',67 'elementHandle',68 'attributes',69 'execute',70 'location',71 ].find(key => key in res);72 if (queryKeyFound) {73 return normalizeQueryResponse(res, queryKeyFound);74 }75 }76 // eval success77 if (isSuccess && isEval) {78 return true;79 }80 // eval failed due assertion error81 if (!isSuccess && isEval && isAssertionError) {82 return false;83 }84 // eval fail85 if (!isSuccess && (isEval || (isTestLine && !isAssertionError))) {86 logger.error(infoMessage());87 throwErr(new SuitestError(message, SuitestError.EVALUATION_ERROR, responseForError));88 }89 // testLine success90 if (isSuccess) {91 if (isSnippet) {92 const snippet = getSnippetLogs({93 verbosity: mapLogLevelsToTranslationModule[verbosity],94 definitions: snippets,95 results: [],96 testId: jsonMessage.request.val,97 level: 1,98 });99 logger.log(snippet);100 return;101 }102 if (isTestLine) {103 return;104 }105 }106 // testLine fail107 if (!isSuccess && isTestLine && isAssertionError) {108 logger.error(infoMessage());109 throwErr(new assert.AssertionError({110 // actual and expected included in message111 message,112 stackStartFn: processServerResponseHandler,113 }));114 }115 // takeScreenshot success116 if (isTakeScreenshot && isSuccess) {117 if (data.dataFormat === 'raw') {118 return res.buffer;119 } else if (data.dataFormat === 'base64') {120 return res.buffer.toString('base64');121 } else if (data.fileName) {122 const dir = path.dirname(data.fileName);123 return fs.promises124 .access(dir)125 .catch(() => fs.promises.mkdir(dir))126 .then(() => fs.promises.writeFile(data.fileName, res.buffer))127 .catch(e => {128 logger.error(e.message);129 throwErr(e);130 });131 }132 return;133 } else if (isTakeScreenshot && !isSuccess) {134 logger.error(infoMessage());135 throwErr(new SuitestError(message, SuitestError.EVALUATION_ERROR, responseForError));136 }137 logger.error(infoMessage(''));138 throwErr(new SuitestError(message, SuitestError.UNKNOWN_ERROR, responseForError));139 };140/**141 * Get socket request type string based on chain data142 * @param {any} data143 * some lines like 'openApp' do not have query type and can't fetch any value from dataGrabber144 * @param {boolean} [hasQuery=true]145 * @returns {'testLine' | 'query' | 'eval'}146 */147const getRequestType = (data, hasQuery = true) => {148 if (data.isAssert) {149 return 'testLine';150 }151 if (152 hasQuery &&153 !data.comparator &&154 !data.isClick &&155 !data.tap &&156 !data.isScroll &&157 !data.isSwipe &&158 !data.isMoveTo &&159 isNil(data.sendText) &&160 isNil(data.setText)161 ) {162 return 'query';163 }164 return 'eval';165};166/**167 * Normalize query chain response return value168 * @param {Object} res169 * @param {string} queryKeyFound170 * @returns {Object|string|undefined}171 */172function normalizeQueryResponse(res, queryKeyFound) {173 if (174 (queryKeyFound === 'elementExists' || queryKeyFound === 'cookieExists')175 && res[queryKeyFound] === false176 ) {177 return void 0;178 }179 return res[queryKeyFound];180}181/**182 * @description return an object with response data for passing into SuitestError183 * @param res184 * @returns {{errorType: (string|*)}}185 */186function getResponseForError(res) {187 const responseForError = {errorType: normalizeErrorType(res)};188 const code = responseMessageCode(res);189 if (code) {190 responseForError.message = {code};191 }192 return responseForError;193}194module.exports = {195 processServerResponse,196 getRequestType,...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...31 subscribe(function() {32 done('Should not onNext');33 },34 function(e) {35 if (isAssertionError(e)) {36 done(e);37 } else {38 done();39 }40 },41 function() {42 done('Should not onComplete');43 });44 });45 it("should get a hard error from the DataSource with some data found in the cache.", function(done) {46 var model = new Model({47 source: new ErrorDataSource(503, "Timeout"),48 cache: {49 test: {50 0: {51 summary: "in cache"52 },53 5: {54 summary: "in cache"55 }56 }57 }58 });59 var count = 0;60 model.61 get(["test", {to: 5}, "summary"]).62 toPathValues().63 doAction(function(x) {64 var expected = {65 path: ["test", count === 0 ? 0 : 5, "summary"],66 value: "in cache"67 };68 count++;69 testRunner.compare(expected, x);70 }, function(err) {71 expect(err.length).to.equal(4);72 // not in boxValue mode73 var expected = {74 path: [],75 value: {76 status: 503,77 message: "Timeout"78 }79 };80 err.forEach(function(e, i) {81 expected.path = ["test", i + 1, "summary"];82 testRunner.compare(expected, e);83 });84 expect(count).to.equals(2);85 }).86 subscribe(noOp,87 function(e) {88 if (isAssertionError(e)) {89 done(e);90 } else {91 done();92 }93 },94 function() {95 done('Should not onComplete');96 });97 });98});99function isAssertionError(e) {100 return e.hasOwnProperty('expected') && e.hasOwnProperty('actual');...

Full Screen

Full Screen

constraints.js

Source:constraints.js Github

copy

Full Screen

...32 this._callback();33 return null;34 } catch (error) {35 this.error = error;36 if (isAssertionError(error)) {37 error.constraint = this.name ? this.name : '[no name]';38 return error;39 }40 throw error;41 }42 }43 enable () {44 this._constraints.reAddConstraint(this);45 }46 disable () {47 this._constraints.removeConstraint(this);48 }49 isActive () {50 return this._active;...

Full Screen

Full Screen

deref.errors.spec.js

Source:deref.errors.spec.js Github

copy

Full Screen

...34 }).35 subscribe(36 noOp,37 function(err) {38 if (isAssertionError(err)) {39 return done(err);40 }41 done();42 },43 done.bind(null, new Error('onCompleted shouldnt be called')));44 });45 });46 it('should throw on invalid input.', function(done) {47 try {48 new Model().deref('testing');49 } catch (e) {50 expect(e.name).toBe(InvalidDerefInputError.name);51 return done();52 }...

Full Screen

Full Screen

process-test-fn-error.js

Source:process-test-fn-error.js Github

copy

Full Screen

1import { sep } from 'path';2import { getCallsiteForError } from './get-callsite';3import { APIError } from './runtime';4import TestCafeErrorList from './error-list';5import {6 UncaughtErrorInTestCode,7 UncaughtNonErrorObjectInTestCode,8 ExternalAssertionLibraryError9} from './test-run';10const INTERNAL = 'internal/';11function isAssertionErrorCallsiteFrame (frame) {12 var filename = frame.getFileName();13 // NOTE: filter out the internals of node.js and assertion libraries14 return filename &&15 filename.indexOf(sep) > -1 &&16 filename.indexOf(INTERNAL) !== 0 &&17 filename.indexOf(`${sep}node_modules${sep}`) < 0;18}19export default function processTestFnError (err) {20 if (err && (err.isTestCafeError || err instanceof TestCafeErrorList))21 return err;22 if (err && err.constructor === APIError)23 return new UncaughtErrorInTestCode(err.rawMessage, err.callsite);24 if (err instanceof Error) {25 var isAssertionError = err.name === 'AssertionError' || err.constructor.name === 'AssertionError';26 // NOTE: assertion libraries can add their source files to the error stack frames.27 // We should skip them to create a correct callsite for the assertion error.28 var callsite = isAssertionError ? getCallsiteForError(err, isAssertionErrorCallsiteFrame) : getCallsiteForError(err);29 return isAssertionError ?30 new ExternalAssertionLibraryError(err, callsite) :31 new UncaughtErrorInTestCode(err, callsite);32 }33 return new UncaughtNonErrorObjectInTestCode(err);...

Full Screen

Full Screen

is-error.js

Source:is-error.js Github

copy

Full Screen

1/**2 * Checks if the given {@link Error} is an assertion error by checking if the class name includes the string 'assert'.3 * @param {Error} error The error to check.4 * @returns {boolean} If the given {@link Error} is an assertion error.5 */6const isAssertionError = function (error) {7 return error.name.toLowerCase().includes('assert') ||8 error.constructor.name.toLowerCase().includes('assert') ||9 error.hasOwnProperty('actual') ||10 error.hasOwnProperty('expected');11};12/**13 * Checks if the given {@link Error} is an assumption error by checking if the class name includes the string 'assum'.14 * @param {Error} error The error to check.15 * @returns {boolean} If the given {@link Error} is an assumption error.16 */17const isAssumptionError = function (error) {18 return error.name.toLowerCase().includes('assum') ||19 error.constructor.name.toLowerCase().includes('assum') ||20 error.hasOwnProperty('actual') ||21 error.hasOwnProperty('expected');22};23module.exports = {24 isAssertionError,25 isAssumptionError...

Full Screen

Full Screen

doneOnError.js

Source:doneOnError.js Github

copy

Full Screen

1var isAssertionError = require('./isAssertionError');2// Convienence function for unit tests and assertion errors.3module.exports = function doneOnError(done) {4 return function(e) {5 if (isAssertionError(e)) {6 return done(e);7 }8 return done();9 };...

Full Screen

Full Screen

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

Run Jest 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