How to use matchArity method in Jest

Best JavaScript code snippet using jest

express.js

Source:express.js Github

copy

Full Screen

1/*2 * Copyright 2020 New Relic Corporation. All rights reserved.3 * SPDX-License-Identifier: Apache-2.04 */5'use strict'6/**7 * Express middleware generates traces where middleware are considered siblings8 * (ended on 'next' invocation) and not nested. Middlware are nested below the9 * routers they are mounted to.10 */11module.exports = function initialize(agent, express, moduleName, shim) {12 if (!express || !express.Router) {13 shim.logger.debug('Could not find Express Router, not instrumenting.')14 return false15 }16 shim.setFramework(shim.EXPRESS)17 shim.setErrorPredicate(function expressErrorPredicate(err) {18 return err !== 'route' && err !== 'router'19 })20 if (express.Router.use) {21 wrapExpress4(shim, express)22 } else {23 wrapExpress3(shim, express)24 }25}26function wrapExpress4(shim, express) {27 // Wrap `use` and `route` which are hung off `Router` directly, not on a28 // prototype.29 shim.wrapMiddlewareMounter(express.Router, 'use', {30 route: shim.FIRST,31 wrapper: wrapMiddleware32 })33 shim.wrapMiddlewareMounter(express.application, 'use', {34 route: shim.FIRST,35 wrapper: wrapMiddleware36 })37 shim.wrap(express.Router, 'route', function wrapRoute(shim, fn) {38 if (!shim.isFunction(fn)) {39 return fn40 }41 return function wrappedRoute() {42 const route = fn.apply(this, arguments)43 // Express should create a new route and layer every time Router#route is44 // called, but just to be on the safe side, make sure we haven't wrapped45 // this already.46 if (!shim.isWrapped(route, 'get')) {47 wrapRouteMethods(shim, route, '')48 const layer = this.stack[this.stack.length - 1]49 // This wraps a 'done' function but not a traditional 'next' function. This allows50 // the route to stay on the stack for middleware nesting after the router.51 // The segment will be automatically ended by the http/https instrumentation.52 shim.recordMiddleware(layer, 'handle', {53 type: shim.ROUTE,54 req: shim.FIRST,55 next: shim.LAST,56 matchArity: true,57 route: route.path58 })59 }60 return route61 }62 })63 shim.wrapMiddlewareMounter(express.Router, 'param', {64 route: shim.FIRST,65 wrapper: function wrapParamware(shim, middleware, fnName, route) {66 return shim.recordParamware(middleware, {67 name: route,68 req: shim.FIRST,69 next: shim.THIRD70 })71 }72 })73 wrapResponse(shim, express.response)74}75function wrapExpress3(shim, express) {76 // In Express 3 the app returned from `express()` is actually a `connect` app77 // which we have no access to before creation. We can not easily wrap the app78 // because there are a lot of methods dangling on it that act on the app itself.79 // Really we just care about apps being used as `request` event listeners on80 // `http.Server` instances so we'll wrap that instead.81 shim.wrapMiddlewareMounter(express.Router.prototype, 'param', {82 route: shim.FIRST,83 wrapper: function wrapParamware(shim, middleware, fnName, route) {84 return shim.recordParamware(middleware, {85 name: route,86 req: shim.FIRST,87 next: shim.THIRD88 })89 }90 })91 shim.wrapMiddlewareMounter(express.Router.prototype, 'use', {92 route: shim.FIRST,93 wrapper: wrapMiddleware94 })95 shim.wrapMiddlewareMounter(express.application, 'use', {96 route: shim.FIRST,97 wrapper: wrapMiddleware98 })99 // NOTE: Do not wrap application route methods in Express 3, they all just100 // forward their arguments to the router.101 wrapRouteMethods(shim, express.Router.prototype, shim.FIRST)102 wrapResponse(shim, express.response)103}104function wrapRouteMethods(shim, route, path) {105 const methods = ['all', 'delete', 'get', 'head', 'opts', 'post', 'put', 'patch']106 shim.wrapMiddlewareMounter(route, methods, { route: path, wrapper: wrapMiddleware })107}108function wrapResponse(shim, response) {109 shim.recordRender(response, 'render', {110 view: shim.FIRST,111 callback: function bindCallback(shim, render, name, segment, args) {112 let cbIdx = shim.normalizeIndex(args.length, shim.LAST)113 if (cbIdx === null) {114 return115 }116 const res = this117 let cb = args[cbIdx]118 if (!shim.isFunction(cb)) {119 ++cbIdx120 cb = function defaultRenderCB(err, str) {121 // https://github.com/expressjs/express/blob/4.x/lib/response.js#L961-L962122 if (err) {123 return res.req.next(err)124 }125 res.send(str)126 }127 args.push(cb)128 }129 args[cbIdx] = shim.bindSegment(cb, segment, true)130 }131 })132}133function wrapMiddleware(shim, middleware, name, route) {134 let method = null135 const spec = {136 route: route,137 type: shim.MIDDLEWARE,138 matchArity: true,139 req: shim.FIRST140 }141 if (middleware.lazyrouter) {142 method = 'handle'143 spec.type = shim.APPLICATION144 } else if (middleware.stack) {145 method = 'handle'146 spec.type = shim.ROUTER147 } else if (middleware.length === 4) {148 spec.type = shim.ERRORWARE149 spec.req = shim.SECOND150 }151 // Express apps just pass their middleware through to their router. We do not152 // want to count the same middleware twice, so we check if it has already been153 // wrapped. Express also wraps apps mounted on apps, so we need to check if154 // this middleware is that app wrapper.155 //156 // NOTE: Express did not name its app wrapper until 4.6.0.157 if (shim.isWrapped(middleware, method) || name === 'mounted_app') {158 // Don't double-wrap middleware159 return middleware160 }161 return shim.recordMiddleware(middleware, method, spec)...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1'use strict'2var hasOwnProperty = require('../../util/properties').hasOwn3var util = require('util')4/**5 * Enumeration of argument indexes.6 *7 * Anywhere that an argument index is used, one of these or a direct integer8 * value can be used. These are just named constants to improve readability.9 *10 * Each of these values is also exposed directly on the DatastoreShim class as11 * static members.12 *13 * @readonly14 * @memberof Shim.prototype15 * @enum {number}16 */17var ARG_INDEXES = {18 FIRST: 0,19 SECOND: 1,20 THIRD: 2,21 FOURTH: 3,22 LAST: -123}24exports.ARG_INDEXES = ARG_INDEXES25exports.cast = cast26exports.MiddlewareSpec = MiddlewareSpec27exports.RecorderSpec = RecorderSpec28exports.SegmentSpec = SegmentSpec29exports.WrapSpec = WrapSpec30function cast(Class, spec) {31 return spec instanceof Class ? spec : new Class(spec)32}33function WrapSpec(spec) {34 this.wrapper = typeof spec === 'function' ? spec : spec.wrapper35 this.matchArity = hasOwnProperty(spec, 'matchArity') ? spec.matchArity : false36}37function SegmentSpec(spec) {38 this.name = hasOwnProperty(spec, 'name') ? spec.name : null39 this.recorder = hasOwnProperty(spec, 'recorder') ? spec.recorder : null40 this.inContext = hasOwnProperty(spec, 'inContext') ? spec.inContext : null41 this.parent = hasOwnProperty(spec, 'parent') ? spec.parent : null42 this.parameters = hasOwnProperty(spec, 'parameters') ? spec.parameters : null43 this.internal = hasOwnProperty(spec, 'internal') ? spec.internal : false44 this.opaque = hasOwnProperty(spec, 'opaque') ? spec.opaque : false45}46function RecorderSpec(spec) {47 SegmentSpec.call(this, spec)48 this.stream = hasOwnProperty(spec, 'stream') ? spec.stream : null49 this.promise = hasOwnProperty(spec, 'promise') ? spec.promise : null50 this.callback = hasOwnProperty(spec, 'callback') ? spec.callback : null51 this.rowCallback = hasOwnProperty(spec, 'rowCallback') ? spec.rowCallback : null52 this.after = hasOwnProperty(spec, 'after') ? spec.after : null53 this.callbackRequired =54 hasOwnProperty(spec, 'callbackRequired') ? spec.callbackRequired : null55}56util.inherits(RecorderSpec, SegmentSpec)57function MiddlewareSpec(spec) {58 RecorderSpec.call(this, spec)59 this.req = hasOwnProperty(spec, 'req' ) ? spec.req : ARG_INDEXES.FIRST60 this.res = hasOwnProperty(spec, 'res' ) ? spec.res : ARG_INDEXES.SECOND61 this.next = hasOwnProperty(spec, 'next' ) ? spec.next : ARG_INDEXES.THIRD62 this.type = hasOwnProperty(spec, 'type' ) ? spec.type : 'MIDDLEWARE'63 this.route = hasOwnProperty(spec, 'route' ) ? spec.route : null64 this.params = hasOwnProperty(spec, 'params') ? spec.params : _defaultGetParams65 this.appendPath = hasOwnProperty(spec, 'appendPath') ? spec.appendPath : true66}67util.inherits(MiddlewareSpec, RecorderSpec)68function _defaultGetParams(shim, fn, name, args, req) {69 return req && req.params...

Full Screen

Full Screen

restify.js

Source:restify.js Github

copy

Full Screen

1/*2 * Copyright 2020 New Relic Corporation. All rights reserved.3 * SPDX-License-Identifier: Apache-2.04 */5'use strict'6module.exports = function initialize(agent, restify, moduleName, shim) {7 shim.setFramework(shim.RESTIFY)8 shim.setRouteParser(function routeParser(shim, fn, fnName, route) {9 return (route && route.path) || route10 })11 let wrappedServerClass = false12 shim.setErrorPredicate(function restifyErrorPredicate(err) {13 return err instanceof Error14 })15 // Restify extends the core http.ServerResponse object when it's loaded,16 // so these methods are separate from core instrumentation.17 const http = require('http')18 const methods = ['send', 'sendRaw', 'redirect']19 shim.wrap(http.ServerResponse.prototype, methods, function wrapMethod(shim, fn) {20 return function wrappedMethod() {21 const segment = shim.getActiveSegment()22 if (segment) {23 // Freezing the name state prevents transaction names from potentially being24 // manipulated by asynchronous response methods executed as part of res.send()25 // but before `next()` is called.26 segment.transaction.nameState.freeze()27 }28 return fn.apply(this, arguments)29 }30 })31 shim.wrapReturn(restify, 'createServer', wrapCreateServer)32 function wrapCreateServer(shim, fn, fnName, server) {33 // If we have not wrapped the server class, now's the time to do that.34 if (server && !wrappedServerClass) {35 wrappedServerClass = true36 wrapServer(Object.getPrototypeOf(server))37 }38 }39 function wrapServer(serverProto) {40 // These are all the methods for mounting routed middleware.41 const routings = ['del', 'get', 'head', 'opts', 'post', 'put', 'patch']42 shim.wrapMiddlewareMounter(serverProto, routings, {43 route: shim.FIRST,44 endpoint: shim.LAST,45 wrapper: function wrapMiddleware(shim, middleware, name, route) {46 if (shim.isWrapped(middleware)) {47 return middleware48 }49 return shim.recordMiddleware(middleware, {50 matchArity: true,51 route,52 req: shim.FIRST,53 next: shim.LAST54 })55 }56 })57 // These methods do not accept a route, just middleware functions.58 const mounters = ['pre', 'use']59 shim.wrapMiddlewareMounter(serverProto, mounters, function wrapper(shim, middleware) {60 if (shim.isWrapped(middleware)) {61 return middleware62 }63 return shim.recordMiddleware(middleware, {64 matchArity: true,65 req: shim.FIRST,66 next: shim.LAST67 })68 })69 }...

Full Screen

Full Screen

connect.js

Source:connect.js Github

copy

Full Screen

1/*2 * Copyright 2020 New Relic Corporation. All rights reserved.3 * SPDX-License-Identifier: Apache-2.04 */5'use strict'6module.exports = function initialize(agent, connect, moduleName, shim) {7 if (!connect) {8 shim.logger.debug('Connect not supplied, not instrumenting.')9 return false10 }11 shim.setFramework(shim.CONNECT)12 shim.setRouteParser(function parseRoute(shim, fn, fnName, route) {13 return route14 })15 const proto =16 (connect && connect.HTTPServer && connect.HTTPServer.prototype) || // v117 (connect && connect.proto) // v218 shim.wrapMiddlewareMounter(proto, 'use', {19 route: shim.FIRST,20 endpoint: shim.LAST,21 wrapper: wrapMiddleware22 })23 wrapConnectExport(shim, connect, !proto)24}25function wrapMiddleware(shim, middleware, name, route) {26 const spec = {27 matchArity: true,28 route: route,29 type: shim.MIDDLEWARE,30 next: shim.LAST,31 req: shim.FIRST32 }33 if (middleware.length === 4) {34 spec.type = shim.ERRORWARE35 spec.req = shim.SECOND36 }37 if (shim.isWrapped(middleware)) {38 // In some cases the middleware will be instrumented by a framework39 // that uses connect (e.g. express v3) and we omit the connect40 // instrumentation.41 return middleware42 }43 return shim.recordMiddleware(middleware, spec)44}45function wrapConnectExport(shim, connect, v3) {46 shim.wrapExport(connect, function wrapExport(shim, fn) {47 const wrapper = shim.wrap(fn, function wrapConnect(shim, _fn) {48 return function wrappedConnect() {49 const res = _fn.apply(this, arguments)50 if (v3) {51 shim.wrapMiddlewareMounter(res, 'use', {52 route: shim.FIRST,53 wrapper: wrapMiddleware54 })55 }56 return res57 }58 })59 shim.proxy(fn, Object.keys(fn), wrapper)60 return wrapper61 })...

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