Best JavaScript code snippet using jest
index.js
Source:index.js
...72 count +73 '`'74 );75};76function stripAddedIndentation(inlineSnapshot) {77 // Find indentation if exists.78 const match = inlineSnapshot.match(INDENTATION_REGEX);79 if (!match || !match[1]) {80 // No indentation.81 return inlineSnapshot;82 }83 const indentation = match[1];84 const lines = inlineSnapshot.split('\n');85 if (lines.length <= 2) {86 // Must be at least 3 lines.87 return inlineSnapshot;88 }89 if (lines[0].trim() !== '' || lines[lines.length - 1].trim() !== '') {90 // If not blank first and last lines, abort.91 return inlineSnapshot;92 }93 for (let i = 1; i < lines.length - 1; i++) {94 if (lines[i] !== '') {95 if (lines[i].indexOf(indentation) !== 0) {96 // All lines except first and last should either be blank or have the same97 // indent as the first line (or more). If this isn't the case we don't98 // want to touch the snapshot at all.99 return inlineSnapshot;100 }101 lines[i] = lines[i].substr(indentation.length);102 }103 } // Last line is a special case because it won't have the same indent as others104 // but may still have been given some indent to line up.105 lines[lines.length - 1] = ''; // Return inline snapshot, now at indent 0.106 inlineSnapshot = lines.join('\n');107 return inlineSnapshot;108}109const fileExists = (filePath, hasteFS) =>110 hasteFS.exists(filePath) || jestExistsFile(filePath);111const cleanup = (hasteFS, update, snapshotResolver, testPathIgnorePatterns) => {112 const pattern = '\\.' + _SnapshotResolver.EXTENSION + '$';113 const files = hasteFS.matchFiles(pattern);114 let testIgnorePatternsRegex = null;115 if (testPathIgnorePatterns && testPathIgnorePatterns.length > 0) {116 testIgnorePatternsRegex = new RegExp(testPathIgnorePatterns.join('|'));117 }118 const list = files.filter(snapshotFile => {119 const testPath = snapshotResolver.resolveTestPath(snapshotFile); // ignore snapshots of ignored tests120 if (testIgnorePatternsRegex && testIgnorePatternsRegex.test(testPath)) {121 return false;122 }123 if (!fileExists(testPath, hasteFS)) {124 if (update === 'all') {125 fs.unlinkSync(snapshotFile);126 }127 return true;128 }129 return false;130 });131 return {132 filesRemoved: list.length,133 filesRemovedList: list134 };135};136const toMatchSnapshot = function (received, propertiesOrHint, hint) {137 const matcherName = 'toMatchSnapshot';138 let properties;139 const length = arguments.length;140 if (length === 2 && typeof propertiesOrHint === 'string') {141 hint = propertiesOrHint;142 } else if (length >= 2) {143 if (typeof propertiesOrHint !== 'object' || propertiesOrHint === null) {144 const options = {145 isNot: this.isNot,146 promise: this.promise147 };148 let printedWithType = (0, _jestMatcherUtils.printWithType)(149 'Expected properties',150 propertiesOrHint,151 _printSnapshot.printExpected152 );153 if (length === 3) {154 options.secondArgument = 'hint';155 options.secondArgumentColor = _jestMatcherUtils.BOLD_WEIGHT;156 if (propertiesOrHint == null) {157 printedWithType += `\n\nTo provide a hint without properties: toMatchSnapshot('hint')`;158 }159 }160 throw new Error(161 (0, _jestMatcherUtils.matcherErrorMessage)(162 (0, _jestMatcherUtils.matcherHint)(163 matcherName,164 undefined,165 _printSnapshot.PROPERTIES_ARG,166 options167 ),168 `Expected ${(0, _jestMatcherUtils.EXPECTED_COLOR)(169 'properties'170 )} must be an object`,171 printedWithType172 )173 );174 } // Future breaking change: Snapshot hint must be a string175 // if (arguments.length === 3 && typeof hint !== 'string') {}176 properties = propertiesOrHint;177 }178 return _toMatchSnapshot({179 context: this,180 hint,181 isInline: false,182 matcherName,183 properties,184 received185 });186};187const toMatchInlineSnapshot = function (188 received,189 propertiesOrSnapshot,190 inlineSnapshot191) {192 const matcherName = 'toMatchInlineSnapshot';193 let properties;194 const length = arguments.length;195 if (length === 2 && typeof propertiesOrSnapshot === 'string') {196 inlineSnapshot = propertiesOrSnapshot;197 } else if (length >= 2) {198 const options = {199 isNot: this.isNot,200 promise: this.promise201 };202 if (length === 3) {203 options.secondArgument = _printSnapshot.SNAPSHOT_ARG;204 options.secondArgumentColor = _printSnapshot.noColor;205 }206 if (207 typeof propertiesOrSnapshot !== 'object' ||208 propertiesOrSnapshot === null209 ) {210 throw new Error(211 (0, _jestMatcherUtils.matcherErrorMessage)(212 (0, _jestMatcherUtils.matcherHint)(213 matcherName,214 undefined,215 _printSnapshot.PROPERTIES_ARG,216 options217 ),218 `Expected ${(0, _jestMatcherUtils.EXPECTED_COLOR)(219 'properties'220 )} must be an object`,221 (0, _jestMatcherUtils.printWithType)(222 'Expected properties',223 propertiesOrSnapshot,224 _printSnapshot.printExpected225 )226 )227 );228 }229 if (length === 3 && typeof inlineSnapshot !== 'string') {230 throw new Error(231 (0, _jestMatcherUtils.matcherErrorMessage)(232 (0, _jestMatcherUtils.matcherHint)(233 matcherName,234 undefined,235 _printSnapshot.PROPERTIES_ARG,236 options237 ),238 `Inline snapshot must be a string`,239 (0, _jestMatcherUtils.printWithType)(240 'Inline snapshot',241 inlineSnapshot,242 utils.serialize243 )244 )245 );246 }247 properties = propertiesOrSnapshot;248 }249 return _toMatchSnapshot({250 context: this,251 inlineSnapshot:252 inlineSnapshot !== undefined253 ? stripAddedIndentation(inlineSnapshot)254 : undefined,255 isInline: true,256 matcherName,257 properties,258 received259 });260};261const _toMatchSnapshot = config => {262 const {263 context,264 hint,265 inlineSnapshot,266 isInline,267 matcherName,268 properties269 } = config;270 let {received} = config;271 context.dontThrow && context.dontThrow();272 const {currentTestName, isNot, snapshotState} = context;273 if (isNot) {274 throw new Error(275 (0, _jestMatcherUtils.matcherErrorMessage)(276 (0, _printSnapshot.matcherHintFromConfig)(config, false),277 NOT_SNAPSHOT_MATCHERS278 )279 );280 }281 if (snapshotState == null) {282 // Because the state is the problem, this is not a matcher error.283 // Call generic stringify from jest-matcher-utils package284 // because uninitialized snapshot state does not need snapshot serializers.285 throw new Error(286 (0, _printSnapshot.matcherHintFromConfig)(config, false) +287 '\n\n' +288 `Snapshot state must be initialized` +289 '\n\n' +290 (0, _jestMatcherUtils.printWithType)(291 'Snapshot state',292 snapshotState,293 _jestMatcherUtils.stringify294 )295 );296 }297 const fullTestName =298 currentTestName && hint299 ? `${currentTestName}: ${hint}`300 : currentTestName || ''; // future BREAKING change: || hint301 if (typeof properties === 'object') {302 if (typeof received !== 'object' || received === null) {303 throw new Error(304 (0, _jestMatcherUtils.matcherErrorMessage)(305 (0, _printSnapshot.matcherHintFromConfig)(config, false),306 `${(0, _jestMatcherUtils.RECEIVED_COLOR)(307 'received'308 )} value must be an object when the matcher has ${(0,309 _jestMatcherUtils.EXPECTED_COLOR)('properties')}`,310 (0, _jestMatcherUtils.printWithType)(311 'Received',312 received,313 _printSnapshot.printReceived314 )315 )316 );317 }318 const propertyPass = context.equals(received, properties, [319 context.utils.iterableEquality,320 context.utils.subsetEquality321 ]);322 if (!propertyPass) {323 const key = snapshotState.fail(fullTestName, received);324 const matched = /(\d+)$/.exec(key);325 const count = matched === null ? 1 : Number(matched[1]);326 const message = () =>327 (0, _printSnapshot.matcherHintFromConfig)(config, false) +328 '\n\n' +329 printSnapshotName(currentTestName, hint, count) +330 '\n\n' +331 (0, _printSnapshot.printPropertiesAndReceived)(332 properties,333 received,334 snapshotState.expand335 );336 return {337 message,338 name: matcherName,339 pass: false340 };341 } else {342 received = utils.deepMerge(received, properties);343 }344 }345 const result = snapshotState.match({346 error: context.error,347 inlineSnapshot,348 isInline,349 received,350 testName: fullTestName351 });352 const {actual, count, expected, pass} = result;353 if (pass) {354 return {355 message: () => '',356 pass: true357 };358 }359 const message =360 expected === undefined361 ? () =>362 (0, _printSnapshot.matcherHintFromConfig)(config, true) +363 '\n\n' +364 printSnapshotName(currentTestName, hint, count) +365 '\n\n' +366 `New snapshot was ${(0, _jestMatcherUtils.BOLD_WEIGHT)(367 'not written'368 )}. The update flag ` +369 `must be explicitly passed to write a new snapshot.\n\n` +370 `This is likely because this test is run in a continuous integration ` +371 `(CI) environment in which snapshots are not written by default.\n\n` +372 `Received:${actual.includes('\n') ? '\n' : ' '}${(0,373 _printSnapshot.bReceivedColor)(actual)}`374 : () =>375 (0, _printSnapshot.matcherHintFromConfig)(config, true) +376 '\n\n' +377 printSnapshotName(currentTestName, hint, count) +378 '\n\n' +379 (0, _printSnapshot.printSnapshotAndReceived)(380 expected,381 actual,382 received,383 snapshotState.expand384 ); // Passing the actual and expected objects so that a custom reporter385 // could access them, for example in order to display a custom visual diff,386 // or create a different error message387 return {388 actual,389 expected,390 message,391 name: matcherName,392 pass: false393 };394};395const toThrowErrorMatchingSnapshot = function (396 received,397 hint, // because error TS1016 for hint?: string398 fromPromise399) {400 const matcherName = 'toThrowErrorMatchingSnapshot'; // Future breaking change: Snapshot hint must be a string401 // if (hint !== undefined && typeof hint !== string) {}402 return _toThrowErrorMatchingSnapshot(403 {404 context: this,405 hint,406 isInline: false,407 matcherName,408 received409 },410 fromPromise411 );412};413const toThrowErrorMatchingInlineSnapshot = function (414 received,415 inlineSnapshot,416 fromPromise417) {418 const matcherName = 'toThrowErrorMatchingInlineSnapshot';419 if (inlineSnapshot !== undefined && typeof inlineSnapshot !== 'string') {420 const options = {421 expectedColor: _printSnapshot.noColor,422 isNot: this.isNot,423 promise: this.promise424 };425 throw new Error(426 (0, _jestMatcherUtils.matcherErrorMessage)(427 (0, _jestMatcherUtils.matcherHint)(428 matcherName,429 undefined,430 _printSnapshot.SNAPSHOT_ARG,431 options432 ),433 `Inline snapshot must be a string`,434 (0, _jestMatcherUtils.printWithType)(435 'Inline snapshot',436 inlineSnapshot,437 utils.serialize438 )439 )440 );441 }442 return _toThrowErrorMatchingSnapshot(443 {444 context: this,445 inlineSnapshot:446 inlineSnapshot !== undefined447 ? stripAddedIndentation(inlineSnapshot)448 : undefined,449 isInline: true,450 matcherName,451 received452 },453 fromPromise454 );455};456const _toThrowErrorMatchingSnapshot = (config, fromPromise) => {457 const {458 context,459 hint,460 inlineSnapshot,461 isInline,...
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.
|<p>it('check_object_of_Car', () => {</p><p>
expect(newCar()).toBeInstanceOf(Car);</p><p>
});</p>|
| :- |
Get 100 minutes of automation test minutes FREE!!