Best JavaScript code snippet using mountebank
sidebars.js
Source:sidebars.js
1module.exports = {2 "someSidebar": [3 {4 "collapsed": true,5 "type": "category",6 "label": "Introduction",7 "items": [8 {9 "type": "doc",10 "id": "introduction/index"11 },12 {13 "type": "doc",14 "id": "introduction/features"15 },16 {17 "type": "doc",18 "id": "introduction/architecture"19 }20 ]21 },22 {23 "collapsed": true,24 "type": "category",25 "label": "System Requirements",26 "items": [27 {28 "type": "doc",29 "id": "system-requirements/hardware/index"30 },31 {32 "collapsed": true,33 "type": "category",34 "label": "Software",35 "items": [36 {37 "type": "doc",38 "id": "system-requirements/software/index"39 },40 {41 "type": "doc",42 "id": "system-requirements/software/git"43 },44 {45 "type": "doc",46 "id": "system-requirements/software/java"47 },48 {49 "type": "doc",50 "id": "system-requirements/software/perl"51 },52 {53 "collapsed": true,54 "type": "category",55 "label": "PostgreSQL",56 "items": [57 {58 "type": "doc",59 "id": "system-requirements/software/postgres/postgres"60 },61 {62 "type": "doc",63 "id": "system-requirements/software/postgres/hikari"64 }65 ]66 },67 {68 "type": "doc",69 "id": "system-requirements/software/tomcat"70 },71 {72 "type": "doc",73 "id": "system-requirements/software/macs"74 },75 {76 "type": "doc",77 "id": "system-requirements/software/solr"78 },79 {80 "collapsed": true,81 "type": "category",82 "label": "Gradle",83 "items": [84 {85 "type": "doc",86 "id": "system-requirements/software/gradle/index"87 },88 {89 "type": "doc",90 "id": "system-requirements/software/gradle/faqs"91 }92 ]93 },94 {95 "type": "doc",96 "id": "system-requirements/software/intellij"97 },98 {99 "type": "doc",100 "id": "system-requirements/software/maven"101 }102 ]103 }104 ]105 },106 {107 "collapsed": true,108 "type": "category",109 "label": "Get started",110 "items": [111 {112 "type": "doc",113 "id": "get-started/tutorial/index"114 },115 {116 "type": "doc",117 "id": "get-started/tutorial/webapp"118 },119 {120 "type": "doc",121 "id": "get-started/tutorial/test-data"122 },123 {124 "type": "doc",125 "id": "get-started/quick-start"126 },127 {128 "type": "doc",129 "id": "get-started/create-your-mine"130 },131 {132 "type": "doc",133 "id": "get-started/testmine"134 },135 {136 "type": "doc",137 "id": "get-started/intermine-tests"138 }139 ]140 },141 {142 "collapsed": true,143 "type": "category",144 "label": "InterMine",145 "items": [146 {147 "type": "doc",148 "id": "intermine/intermine"149 },150 {151 "type": "doc",152 "id": "intermine/upgrade"153 },154 {155 "type": "doc",156 "id": "intermine/roadmap"157 },158 {159 "type": "doc",160 "id": "intermine/intermine-versions"161 },162 {163 "type": "doc",164 "id": "intermine/javadoc/index"165 },166 {167 "type": "doc",168 "id": "intermine/get-involved"169 },170 {171 "type": "doc",172 "id": "intermine/amazon"173 }174 ]175 },176 {177 "collapsed": true,178 "type": "category",179 "label": "Data Model",180 "items": [181 {182 "type": "doc",183 "id": "data-model/overview"184 },185 {186 "type": "doc",187 "id": "data-model/model"188 },189 {190 "type": "doc",191 "id": "data-model/data-labels"192 },193 {194 "type": "doc",195 "id": "api/pathquery"196 },197 {198 "type": "doc",199 "id": "data-model/overlaps"200 },201 {202 "type": "doc",203 "id": "data-model/model-ontologies"204 }205 ]206 },207 {208 "collapsed": true,209 "type": "category",210 "label": "Database",211 "items": [212 {213 "type": "doc",214 "id": "database/download-scripts"215 },216 {217 "collapsed": true,218 "type": "category",219 "label": "Data Sources",220 "items": [221 {222 "collapsed": true,223 "type": "category",224 "label": "Data Source Library",225 "items": [226 {227 "type": "doc",228 "id": "database/data-sources/library/index"229 },230 {231 "collapsed": true,232 "type": "category",233 "label": "Gene Ontology",234 "items": [235 {236 "type": "doc",237 "id": "database/data-sources/library/go/go-annotation"238 },239 {240 "type": "doc",241 "id": "database/data-sources/library/go/go-obo"242 }243 ]244 },245 {246 "collapsed": true,247 "type": "category",248 "label": "Homologue Data Sources",249 "items": [250 {251 "type": "doc",252 "id": "database/data-sources/library/homologues/index"253 },254 {255 "type": "doc",256 "id": "database/data-sources/library/homologues/treefam"257 },258 {259 "type": "doc",260 "id": "database/data-sources/library/homologues/homologene"261 },262 {263 "type": "doc",264 "id": "database/data-sources/library/homologues/orthodb"265 },266 {267 "type": "doc",268 "id": "database/data-sources/library/homologues/panther"269 },270 {271 "type": "doc",272 "id": "database/data-sources/library/homologues/compara"273 }274 ]275 },276 {277 "collapsed": true,278 "type": "category",279 "label": "Interactions",280 "items": [281 {282 "type": "doc",283 "id": "database/data-sources/library/interactions/biogrid"284 },285 {286 "type": "doc",287 "id": "database/data-sources/library/interactions/intact"288 },289 {290 "type": "doc",291 "id": "database/data-sources/library/interactions/intact-complexes"292 },293 {294 "type": "doc",295 "id": "database/data-sources/library/interactions/psi-mi-ontology"296 }297 ]298 },299 {300 "collapsed": true,301 "type": "category",302 "label": "Pathway data sources",303 "items": [304 {305 "type": "doc",306 "id": "database/data-sources/library/pathways/kegg"307 },308 {309 "type": "doc",310 "id": "database/data-sources/library/pathways/reactome"311 }312 ]313 },314 {315 "collapsed": true,316 "type": "category",317 "label": "Proteins",318 "items": [319 {320 "type": "doc",321 "id": "database/data-sources/library/proteins/uniprot"322 },323 {324 "type": "doc",325 "id": "database/data-sources/library/proteins/interpro"326 }327 ]328 },329 {330 "collapsed": true,331 "type": "category",332 "label": "Publications",333 "items": [334 {335 "type": "doc",336 "id": "database/data-sources/library/publications/pubmed"337 },338 {339 "type": "doc",340 "id": "database/data-sources/library/publications/publications"341 }342 ]343 },344 {345 "type": "doc",346 "id": "database/data-sources/library/ncbi-gene"347 },348 {349 "type": "doc",350 "id": "database/data-sources/library/chado"351 },352 {353 "type": "doc",354 "id": "database/data-sources/library/fasta"355 },356 {357 "type": "doc",358 "id": "database/data-sources/library/gff"359 },360 {361 "type": "doc",362 "id": "database/data-sources/library/identifiers/index"363 },364 {365 "type": "doc",366 "id": "database/data-sources/library/intermine-items-xml"367 },368 {369 "type": "doc",370 "id": "database/data-sources/library/omim"371 },372 {373 "type": "doc",374 "id": "database/data-sources/library/organism"375 },376 {377 "type": "doc",378 "id": "database/data-sources/library/so"379 },380 {381 "type": "doc",382 "id": "database/data-sources/library/uberon"383 },384 {385 "type": "doc",386 "id": "database/data-sources/library/data-sources"387 },388 {389 "type": "doc",390 "id": "database/data-sources/library/data-sets"391 },392 {393 "type": "doc",394 "id": "database/data-sources/library/variation/vcf"395 }396 ]397 },398 {399 "type": "doc",400 "id": "database/data-sources/custom/index"401 },402 {403 "collapsed": true,404 "type": "category",405 "label": "InterMine Items XML",406 "items": [407 {408 "type": "doc",409 "id": "database/data-sources/apis/index"410 },411 {412 "type": "doc",413 "id": "database/data-sources/apis/java-items-api"414 },415 {416 "type": "doc",417 "id": "database/data-sources/apis/perl-items-api"418 },419 {420 "type": "doc",421 "id": "database/data-sources/apis/python-items-api"422 }423 ]424 },425 {426 "type": "doc",427 "id": "database/data-sources/id-resolvers"428 },429 {430 "type": "doc",431 "id": "database/data-sources/data-licences"432 }433 ]434 },435 {436 "collapsed": true,437 "type": "category",438 "label": "Database Building",439 "items": [440 {441 "type": "doc",442 "id": "database/database-building/index"443 },444 {445 "type": "doc",446 "id": "database/database-building/build-script"447 },448 {449 "type": "doc",450 "id": "database/database-building/project-xml"451 },452 {453 "type": "doc",454 "id": "database/database-building/data-integration"455 },456 {457 "type": "doc",458 "id": "database/database-building/model-merging"459 },460 {461 "type": "doc",462 "id": "database/database-building/primary-keys"463 },464 {465 "type": "doc",466 "id": "database/database-building/priority-config"467 },468 {469 "type": "doc",470 "id": "database/database-building/post-processing/index"471 },472 {473 "type": "doc",474 "id": "database/database-building/post-build-updating-with-sql-triggers"475 },476 {477 "type": "doc",478 "id": "database/database-building/debugging"479 }480 ]481 },482 {483 "collapsed": true,484 "type": "category",485 "label": "Data Integrity Checks",486 "items": [487 {488 "type": "doc",489 "id": "database/data-integrity-checks/template-comparison"490 },491 {492 "type": "doc",493 "id": "database/data-integrity-checks/acceptance-tests"494 }495 ]496 },497 {498 "collapsed": true,499 "type": "category",500 "label": "InterMine performance",501 "items": [502 {503 "type": "doc",504 "id": "database/performance/data-loading"505 },506 {507 "type": "doc",508 "id": "database/performance/precomputing"509 },510 {511 "type": "doc",512 "id": "database/performance/configuration"513 }514 ]515 }516 ]517 },518 {519 "collapsed": true,520 "type": "category",521 "label": "Web Application",522 "items": [523 {524 "type": "doc",525 "id": "webapp/bluegenes/index"526 },527 {528 "type": "doc",529 "id": "webapp/layout/index"530 },531 {532 "type": "doc",533 "id": "webapp/homepage/index"534 },535 {536 "collapsed": true,537 "type": "category",538 "label": "Report Page",539 "items": [540 {541 "type": "doc",542 "id": "webapp/report-page/permanentURL"543 }544 ]545 },546 {547 "collapsed": true,548 "type": "category",549 "label": "Lists",550 "items": [551 {552 "type": "doc",553 "id": "webapp/lists/lists-page"554 },555 {556 "type": "doc",557 "id": "webapp/lists/list-upload"558 },559 {560 "type": "doc",561 "id": "webapp/lists/list-upgrade"562 },563 {564 "collapsed": true,565 "type": "category",566 "label": "List widgets",567 "items": [568 {569 "type": "doc",570 "id": "webapp/lists/list-widgets/index"571 },572 {573 "type": "doc",574 "id": "webapp/lists/list-widgets/embedding"575 },576 {577 "type": "doc",578 "id": "webapp/lists/list-widgets/enrichment-widgets"579 }580 ]581 }582 ]583 },584 {585 "type": "doc",586 "id": "webapp/template-queries/index"587 },588 {589 "type": "doc",590 "id": "webapp/query-results/index"591 },592 {593 "type": "doc",594 "id": "webapp/query-builder/index"595 },596 {597 "type": "doc",598 "id": "webapp/keyword-search/index"599 },600 {601 "collapsed": true,602 "type": "category",603 "label": "Customise Web Application",604 "items": [605 {606 "type": "doc",607 "id": "webapp/properties/web-properties"608 },609 {610 "type": "doc",611 "id": "webapp/properties/oauth2"612 },613 {614 "type": "doc",615 "id": "webapp/properties/webconfig-model"616 },617 {618 "type": "doc",619 "id": "webapp/properties/class-keys"620 }621 ]622 },623 {624 "type": "doc",625 "id": "webapp/markup/index"626 },627 {628 "type": "doc",629 "id": "webapp/https"630 },631 {632 "type": "doc",633 "id": "webapp/jbrowse"634 },635 {636 "collapsed": true,637 "type": "category",638 "label": "Tool API",639 "items": [640 {641 "type": "doc",642 "id": "webapp/tool-api/overview"643 },644 {645 "type": "doc",646 "id": "webapp/tool-api/tutorial"647 },648 {649 "type": "doc",650 "id": "webapp/tool-api/specification"651 }652 ]653 },654 {655 "collapsed": true,656 "type": "category",657 "label": "Monitoring Site Usage",658 "items": [659 {660 "type": "doc",661 "id": "webapp/monitoring-site-usage/google-analytics"662 }663 ]664 },665 {666 "type": "doc",667 "id": "webapp/admin/index"668 },669 {670 "collapsed": true,671 "type": "category",672 "label": "User Accounts",673 "items": [674 {675 "type": "doc",676 "id": "webapp/user-accounts/userprofile"677 }678 ]679 },680 {681 "type": "doc",682 "id": "webapp/frictionless/index"683 }684 ]685 },686 {687 "collapsed": true,688 "type": "category",689 "label": "Web Services",690 "items": [691 { 692 "type": "doc",693 "id": "web-services/index"694 },695 {696 "type": "doc",697 "id": "web-services/intermine-properties"698 },699 { 700 "type": "doc",701 "id": "web-services/authentication"702 },703 {704 "type": "doc",705 "id": "web-services/diagnostic"706 },707 {708 "type": "doc",709 "id": "web-services/iodocs"710 }]711 },712 {713 "collapsed": true,714 "type": "category",715 "label": "Support",716 "items": [717 {718 "type": "doc",719 "id": "support/mailing-list"720 },721 {722 "type": "doc",723 "id": "support/troubleshooting-tips"724 }725 ]726 },727 {728 "collapsed": true,729 "type": "category",730 "label": "About Us",731 "items": [732 {733 "type": "doc",734 "id": "about/index"735 },736 {737 "type": "doc",738 "id": "about/contact-us"739 },740 {741 "type": "doc",742 "id": "about/privacy-policy"743 }744 ]745 }746 ]...
Doc.test.jsx
Source:Doc.test.jsx
1const extensions = require('@readme/oas-extensions');2const { Request, Response } = require('node-fetch');3const Oas = require('oas');4const { Button, Tabs } = require('@readme/ui/.bundles/es/ui/components');5const { TutorialModal, TutorialTile } = require('@readme/ui/.bundles/es/ui/compositions');6const { cmVariableContext: TutorialVariableContext } = require('@readme/ui/.bundles/es/views');7const { DEFAULT_TUTORIAL } = require('@readme/ui/.bundles/es/ui/compositions/Tutorials/Modal/constants/stepDefaults');8global.Request = Request;9const React = require('react');10const { shallow, mount } = require('enzyme');11const Doc = require('../src/Doc');12const ErrorBoundary = require('../src/ErrorBoundary');13const petstore = require('@readme/oas-examples/3.0/json/petstore.json');14const uspto = require('@readme/oas-examples/3.0/json/uspto.json');15const petstoreWithAuth = require('./__fixtures__/petstore/oas.json');16const multipleSecurities = require('./__fixtures__/multiple-securities/oas.json');17const oas = new Oas(petstore);18const props = {19 auth: {},20 doc: {21 api: { method: 'get' },22 formData: { path: { petId: '1' }, auth: { api_key: '' } },23 slug: 'slug',24 swagger: { path: '/pet/{petId}' },25 title: 'Title',26 type: 'endpoint',27 },28 language: 'node',29 lazy: false,30 oas,31 oauth: false,32 onAuthChange: () => {},33 onAuthGroupChange: () => {},34 setLanguage: () => {},35 suggestedEdits: false,36 tryItMetrics: () => {},37 ui: {38 Button,39 Tabs,40 tutorials: {41 DEFAULT_TUTORIAL,42 TutorialModal,43 TutorialTile,44 TutorialVariableContext,45 },46 },47};48const petExample = {49 category: {50 id: 0,51 name: 'string',52 },53 name: 'doggie',54 photoUrls: ['string'],55 status: 'available',56 tags: [57 {58 id: 0,59 name: 'string',60 },61 ],62};63function assertDocElements(component, doc) {64 expect(component.find(`#page-${doc.slug}`)).toHaveLength(1);65 expect(component.find('a.anchor-page-title')).toHaveLength(1);66 expect(component.find('h2').text()).toBe(doc.title);67}68beforeAll(async () => {69 await oas.dereference();70});71test('should output a div', () => {72 const doc = shallow(<Doc {...props} />);73 doc.setState({ showEndpoint: true });74 assertDocElements(doc, props.doc);75 expect(doc.find('.hub-api')).toHaveLength(1);76 expect(doc.find('PathUrl')).toHaveLength(1);77 expect(doc.find('CodeSample')).toHaveLength(1);78 // This test needs the component to be `mount()`ed but for some reason when I mount in this test it makes the test79 // below that uses `jest.useFakeTimers()` fail ¯\_(ã)_/¯. Skipping for now.80 // expect(doc.find('Params').length).toBe(1);81 expect(doc.find('Content')).toHaveLength(1);82});83test('should render straight away if `appearance.splitReferenceDocs` is true', () => {84 const doc = mount(85 <Doc86 {...props}87 appearance={{88 splitReferenceDocs: true,89 }}90 />91 );92 expect(doc.find('Waypoint')).toHaveLength(0);93});94test('should render a manual endpoint', () => {95 const doc = JSON.parse(JSON.stringify(props.doc));96 doc.api = {97 ...doc.api,98 examples: {99 codes: [],100 },101 params: [102 {103 default: 'test',104 desc: 'test',105 in: 'path',106 name: 'test',107 ref: '',108 required: false,109 type: 'string',110 },111 ],112 };113 const node = mount(114 <Doc115 {...props}116 appearance={{117 splitReferenceDocs: true,118 }}119 doc={doc}120 oas={props.oas}121 />122 );123 assertDocElements(node, doc);124 expect(node.find('Params')).toHaveLength(1);125});126test('should work without a doc.swagger/doc.path/oas', () => {127 const doc = { title: 'title', slug: 'slug', type: 'basic' };128 const docComponent = shallow(129 <Doc130 auth={{}}131 doc={doc}132 language="node"133 oas={new Oas()}134 oauth={false}135 onAuthChange={() => {}}136 onAuthGroupChange={() => {}}137 setLanguage={() => {}}138 suggestedEdits139 tryItMetrics={() => {}}140 />141 );142 expect(docComponent.find('Waypoint')).toHaveLength(1);143 docComponent.setState({ showEndpoint: true });144 assertDocElements(docComponent, doc);145 expect(docComponent.find('.hub-api')).toHaveLength(0);146 expect(docComponent.find('Content')).toHaveLength(1);147});148test('should still display `Content` with column-style layout', () => {149 const doc = { title: 'title', slug: 'slug', type: 'basic' };150 const docComponent = shallow(151 <Doc152 appearance={{ referenceLayout: 'column' }}153 auth={{}}154 doc={doc}155 language="node"156 oas={new Oas()}157 oauth={false}158 onAuthChange={() => {}}159 onAuthGroupChange={() => {}}160 setLanguage={() => {}}161 suggestedEdits162 tryItMetrics={() => {}}163 />164 );165 docComponent.setState({ showEndpoint: true });166 assertDocElements(docComponent, doc);167 expect(docComponent.find('.hub-api')).toHaveLength(1);168 expect(docComponent.find('Content')).toHaveLength(2);169});170describe('state.dirty', () => {171 it('should default to false', () => {172 const doc = shallow(<Doc {...props} />);173 expect(doc.state('dirty')).toStrictEqual({ form: false, json: false });174 });175 it('should switch to true on form change', () => {176 const doc = shallow(<Doc {...props} />);177 doc.instance().onChange({ a: 1 });178 expect(doc.state('dirty')).toStrictEqual({ form: true, json: false });179 });180});181describe('onSubmit', () => {182 const { fetch } = window;183 afterEach(() => {184 window.fetch = fetch;185 });186 it('should display authentication warning if auth is required for endpoint', () => {187 jest.useFakeTimers();188 const petstoreWithAuthOas = new Oas(petstoreWithAuth);189 const doc = mount(<Doc {...props} oas={petstoreWithAuthOas} />);190 doc.instance().onSubmit();191 expect(doc.state('showAuthBox')).toBe(true);192 jest.runAllTimers();193 expect(doc.state('needsAuth')).toBe(true);194 });195 it('should make request on Submit', async () => {196 expect.assertions(3);197 const petstoreWithAuthOas = new Oas(petstoreWithAuth);198 await petstoreWithAuthOas.dereference();199 const props2 = {200 auth: { petstore_auth: 'api-key' },201 doc: {202 title: 'Title',203 slug: 'slug',204 type: 'endpoint',205 swagger: { path: '/pet' },206 api: { method: 'post' },207 formData: {208 body: {209 name: '1',210 photoUrls: ['1'],211 },212 },213 onSubmit: () => {},214 },215 language: 'node',216 oas: petstoreWithAuthOas,217 oauth: false,218 setLanguage: () => {},219 };220 window.fetch = request => {221 expect(request.url).toContain(petstoreWithAuthOas.servers[0].url);222 return Promise.resolve(223 new Response(JSON.stringify({ id: 1 }), {224 headers: { 'content-type': 'application/json' },225 })226 );227 };228 const doc = mount(<Doc {...props} {...props2} />);229 return doc230 .instance()231 .onSubmit()232 .then(() => {233 expect(doc.state('loading')).toBe(false);234 expect(doc.state('result')).not.toBeNull();235 });236 });237 it('should make request to the proxy url if necessary', () => {238 expect.assertions(1);239 const proxyOas = new Oas({240 servers: [{ url: 'http://example.com' }],241 'x-readme': {242 [extensions.PROXY_ENABLED]: true,243 },244 paths: {245 '/pet/{petId}': {246 get: {247 responses: {248 default: {249 description: 'desc',250 },251 },252 },253 },254 },255 });256 const doc = mount(<Doc {...props} oas={proxyOas} />);257 window.fetch = request => {258 expect(request.url).toContain(`https://try.readme.io/${proxyOas.servers[0].url}`);259 return Promise.resolve(new Response());260 };261 return doc.instance().onSubmit();262 });263 it('should call `tryItMetrics` on success', async () => {264 const tryItMetrics = jest.fn();265 const doc = mount(<Doc {...props} auth={{ api_key: 'api-key' }} tryItMetrics={tryItMetrics} />);266 window.fetch = () => {267 return Promise.resolve(new Response());268 };269 await doc.instance().onSubmit();270 expect(tryItMetrics).toHaveBeenCalled();271 });272});273describe('toggleAuth', () => {274 it('toggleAuth should change state of showAuthBox', () => {275 const doc = shallow(<Doc {...props} />);276 expect(doc.state('showAuthBox')).toBe(false);277 doc.instance().toggleAuth({ preventDefault() {} });278 expect(doc.state('showAuthBox')).toBe(true);279 doc.instance().toggleAuth({ preventDefault() {} });280 expect(doc.state('showAuthBox')).toBe(false);281 });282});283describe('state.loading', () => {284 it('should default to false', () => {285 const doc = shallow(<Doc {...props} />);286 expect(doc.state('loading')).toBe(false);287 });288});289describe('suggest edits', () => {290 it('should not show if suggestedEdits is false', () => {291 const doc = shallow(<Doc {...props} suggestedEdits={false} />);292 expect(doc.find('a.hub-reference-edit.pull-right')).toHaveLength(0);293 });294 it('should show icon if suggested edits is true', () => {295 const doc = shallow(<Doc {...props} suggestedEdits />);296 expect(doc.find('a.hub-reference-edit.pull-right')).toHaveLength(1);297 });298 it('should have child project if baseUrl is set', () => {299 const doc = shallow(<Doc {...{ baseUrl: '/child', ...props }} suggestedEdits />);300 expect(doc.find('a.hub-reference-edit.pull-right').prop('href')).toBe(`/child/reference-edit/${props.doc.slug}`);301 });302});303describe('ResponseSchema', () => {304 it('should render ResponseSchema if endpoint does have a response', async () => {305 const petstoreWithAuthOas = new Oas(petstoreWithAuth);306 await petstoreWithAuthOas.dereference();307 const doc = shallow(<Doc {...props} oas={petstoreWithAuthOas} />);308 doc.setState({ showEndpoint: true });309 expect(doc.find('ResponseSchema')).toHaveLength(1);310 });311 it('should not render ResponseSchema if endpoint does not have a response', async () => {312 const multipleSecuritiesOas = new Oas(multipleSecurities);313 await multipleSecuritiesOas.dereference();314 const doc = shallow(315 <Doc316 {...props}317 doc={{318 title: 'Title',319 slug: 'slug',320 type: 'endpoint',321 swagger: { path: '/unknown-scheme' },322 api: { method: 'post' },323 }}324 oas={multipleSecuritiesOas}325 />326 );327 expect(doc.find('ResponseSchema')).toHaveLength(0);328 });329});330describe('RenderLogs', () => {331 it('should return a log component', () => {332 const doc = shallow(<Doc {...props} Logs={() => {}} />);333 const res = doc.instance().renderLogs();334 expect(typeof res).toBe('object');335 });336});337describe('themes', () => {338 it('should output code samples and responses in the right column', () => {339 const doc = shallow(<Doc {...props} appearance={{ referenceLayout: 'column' }} />);340 doc.setState({ showEndpoint: true });341 expect(doc.find('.hub-reference-right').find('CodeSample')).toHaveLength(1);342 expect(doc.find('.hub-reference-right').find('Response')).toHaveLength(1);343 });344});345describe('error handling', () => {346 const brokenOas = new Oas({347 paths: {348 '/path': {349 post: {350 requestBody: {351 $ref: '#/components/schemas/UnknownSchema',352 },353 },354 },355 },356 });357 const docProps = {358 title: 'title',359 slug: 'slug',360 type: 'endpoint',361 swagger: { path: '/path' },362 api: { method: 'post' },363 };364 const originalConsole = console;365 // We're testing errors here, so we don't need `console.error` logs spamming the test output.366 beforeEach(() => {367 // eslint-disable-next-line no-console368 console.error = () => {};369 });370 afterEach(() => {371 // eslint-disable-next-line no-console372 console.error = originalConsole.error;373 });374 it('should output with a masked error message if the endpoint fails to load', () => {375 const doc = mount(<Doc {...props} doc={docProps} maskErrorMessages={true} oas={brokenOas} />);376 expect(doc.find(ErrorBoundary)).toHaveLength(1);377 const html = doc.html();378 expect(html).not.toMatch('support@readme.io');379 expect(html).toMatch("endpoint's documentation");380 });381 describe('support-focused error messaging', () => {382 it('should output with an error message if the endpoint fails to load, with a unique error event id', () => {383 const doc = mount(<Doc {...props} doc={docProps} maskErrorMessages={false} oas={brokenOas} />);384 doc.setState({ showEndpoint: true });385 const html = doc.html();386 expect(doc.find(ErrorBoundary)).toHaveLength(1);387 expect(html).toMatch('support@readme.io');388 expect(html).toMatch("endpoint's documentation");389 });390 });391 it('should call the onError handler', () => {392 const mockErrorHandler = jest.fn();393 const doc = mount(394 <Doc {...props} doc={docProps} maskErrorMessages={false} oas={brokenOas} onError={() => mockErrorHandler()} />395 );396 doc.setState({ showEndpoint: true });397 const html = doc.html();398 expect(mockErrorHandler).toHaveBeenCalled();399 expect(doc.find(ErrorBoundary)).toHaveLength(1);400 expect(html).toMatch('support@readme.io');401 expect(html).toMatch("endpoint's documentation");402 expect(html).toMatch(/ERR-([0-9A-Z]{6})/);403 });404});405describe('#enableRequestBodyJsonEditor', () => {406 it('should not show the editor on an operation without a request body', () => {407 const doc = shallow(<Doc {...props} enableRequestBodyJsonEditor={true} />);408 expect(doc.find('Tabs')).toHaveLength(0);409 });410 it('should not show the editor on an operation with a non-json request body', async () => {411 const usptoOas = new Oas(uspto);412 await usptoOas.dereference();413 const doc = mount(414 <Doc415 {...props}416 doc={{417 ...props.doc,418 api: { method: 'post' },419 swagger: { path: '/{dataset}/{version}/records' },420 }}421 enableRequestBodyJsonEditor={true}422 oas={usptoOas}423 />424 );425 expect(doc.find('Tabs')).toHaveLength(0);426 });427 it('should show the editor on an operation with a json-compatible request body', () => {428 const doc = mount(429 <Doc430 {...props}431 doc={{432 ...props.doc,433 api: { method: 'post' },434 swagger: { path: '/pet' },435 }}436 enableRequestBodyJsonEditor={true}437 oas={oas}438 />439 );440 expect(doc.find('Tabs')).toHaveLength(1);441 });442 describe('#formDataJson', () => {443 it('should fill formDataJson with an example request body', () => {444 const doc = mount(445 <Doc446 {...props}447 doc={{448 ...props.doc,449 api: { method: 'post' },450 swagger: { path: '/pet' },451 }}452 enableRequestBodyJsonEditor={true}453 oas={oas}454 />455 );456 expect(doc.state('formDataJson')).toStrictEqual(petExample);457 expect(doc.state('formDataJsonOriginal')).toStrictEqual(doc.state('formDataJson'));458 expect(doc.state('formDataJsonRaw')).toMatch('"status": "available"');459 });460 });461});462describe('#resetForm()', () => {463 it('should reset formDataJson', () => {464 const doc = mount(465 <Doc466 {...props}467 doc={{468 ...props.doc,469 api: { method: 'post' },470 swagger: { path: '/pet' },471 }}472 enableRequestBodyJsonEditor={true}473 oas={oas}474 />475 );476 expect(doc.state('formDataJson')).toStrictEqual(petExample);477 doc.setState({ formDataJson: { name: 'buster' } });478 doc.instance().resetForm();479 expect(doc.state('formDataJson')).toStrictEqual(petExample);480 expect(doc.state('formDataJsonRaw')).toMatch('"status": "available"');481 expect(doc.state('validationErrors')).toStrictEqual({ form: false, json: false });482 expect(doc.state('dirty')).toStrictEqual({ form: true, json: false });483 });484});485describe('#onJsonChange()', () => {486 it('should update formDataJson when given valid json', () => {487 const doc = shallow(488 <Doc489 {...props}490 doc={{491 ...props.doc,492 api: { method: 'post' },493 swagger: { path: '/pet' },494 }}495 enableRequestBodyJsonEditor={true}496 oas={oas}497 />498 );499 doc.instance().onJsonChange(JSON.stringify({ name: 'buster' }));500 expect(doc.state('formDataJson')).toStrictEqual({ name: 'buster' });501 expect(doc.state('formDataJsonRaw')).toStrictEqual(JSON.stringify({ name: 'buster' }));502 expect(doc.state('validationErrors')).toStrictEqual({ form: false, json: false });503 expect(doc.state('dirty')).toStrictEqual({ form: false, json: true });504 });505 it('should set validation errors when given invalid JSON', () => {506 const doc = shallow(507 <Doc508 {...props}509 doc={{510 ...props.doc,511 api: { method: 'post' },512 swagger: { path: '/pet' },513 }}514 enableRequestBodyJsonEditor={true}515 oas={oas}516 />517 );518 doc.instance().onJsonChange(JSON.stringify({ name: 'buster' }));519 doc.instance().onJsonChange('{ invalid json }');520 expect(doc.state('formDataJson')).toStrictEqual({ name: 'buster' });521 expect(doc.state('formDataJsonRaw')).toStrictEqual('{ invalid json }');522 expect(doc.state('validationErrors')).toStrictEqual({523 form: false,524 json: expect.any(String),525 });526 expect(doc.state('dirty')).toStrictEqual({ form: false, json: true });527 });528});529describe('#onModeChange()', () => {530 it('should change the editing mode', () => {531 const doc = shallow(<Doc {...props} />);532 expect(doc.state('editingMode')).toBe('form');533 doc.instance().onModeChange('JSON');534 expect(doc.state('editingMode')).toBe('json');535 });536});537describe('#isDirty()', () => {538 it('should return a dirty state based on the current editing mode', () => {539 const doc = shallow(<Doc {...props} />);540 doc.setState({ dirty: { form: true, json: false } });541 expect(doc.instance().isDirty()).toBe(true);542 doc.setState({ editingMode: 'json' });543 expect(doc.instance().isDirty()).toBe(false);544 });545});546describe('#getValidationErrors()', () => {547 it('should return validation errors based on the current editing mode', () => {548 const doc = shallow(<Doc {...props} />);549 doc.setState({ validationErrors: { form: false, json: 'invalid json' } });550 expect(doc.instance().getValidationErrors()).toBe(false);551 doc.setState({ editingMode: 'json' });552 expect(doc.instance().getValidationErrors()).toBe('invalid json');553 });554});555describe('#getFormDataForCurrentMode()', () => {556 it('should pull back the appropriate form data for the current editing mode', () => {557 const doc = shallow(<Doc {...props} />);558 doc.setState({559 formData: {560 headers: {561 'x-breed': 'pug',562 },563 body: {564 name: 'booster',565 },566 },567 formDataJson: {568 name: 'buster',569 },570 });571 expect(doc.instance().getFormDataForCurrentMode()).toStrictEqual({572 headers: { 'x-breed': 'pug' },573 body: { name: 'booster' },574 });575 doc.setState({ editingMode: 'json' });576 expect(doc.instance().getFormDataForCurrentMode()).toStrictEqual({577 headers: { 'x-breed': 'pug' },578 body: { name: 'buster' },579 });580 });...
stock_entry.js
Source:stock_entry.js
...173 this.frm.add_custom_button(__("Make Excise Invoice"), function() {174 var excise = frappe.model.make_new_doc_and_get_name('Journal Voucher');175 excise = locals['Journal Voucher'][excise];176 excise.voucher_type = 'Excise Voucher';177 loaddoc('Journal Voucher', excise.name);178 }, frappe.boot.doctype_icons["Journal Voucher"], "btn-default");179 },180 make_return_jv: function() {181 if(this.get_doctype_docname()) {182 return this.frm.call({183 method: "make_return_jv",184 args: {185 stock_entry: this.frm.doc.name186 },187 callback: function(r) {188 if(!r.exc) {189 var doclist = frappe.model.sync(r.message);190 frappe.set_route("Form", doclist[0].doctype, doclist[0].name);191 }192 }193 });194 }195 },196 mtn_details_add: function(doc, cdt, cdn) {197 var row = frappe.get_doc(cdt, cdn);198 this.frm.script_manager.copy_from_first_row("mtn_details", row,199 ["expense_account", "cost_center"]);200 if(!row.s_warehouse) row.s_warehouse = this.frm.doc.from_warehouse;201 if(!row.t_warehouse) row.t_warehouse = this.frm.doc.to_warehouse;202 },203 source_mandatory: ["Material Issue", "Material Transfer", "Purchase Return"],204 target_mandatory: ["Material Receipt", "Material Transfer", "Sales Return"],205 from_warehouse: function(doc) {206 var me = this;207 this.set_warehouse_if_missing("s_warehouse", doc.from_warehouse, function(row) {208 return me.source_mandatory.indexOf(me.frm.doc.purpose)!==-1;209 });210 },211 to_warehouse: function(doc) {...
journal_voucher.js
Source:journal_voucher.js
...35 });36 $.each([["against_voucher", "Purchase Invoice", "credit_to"],37 ["against_invoice", "Sales Invoice", "debit_to"]], function(i, opts) {38 me.frm.set_query(opts[0], "entries", function(doc, cdt, cdn) {39 var jvd = frappe.get_doc(cdt, cdn);40 frappe.model.validate_missing(jvd, "account");41 return {42 filters: [43 [opts[1], opts[2], "=", jvd.account],44 [opts[1], "docstatus", "=", 1],45 [opts[1], "outstanding_amount", ">", 0]46 ]47 };48 });49 });50 this.frm.set_query("against_jv", "entries", function(doc, cdt, cdn) {51 var jvd = frappe.get_doc(cdt, cdn);52 frappe.model.validate_missing(jvd, "account");53 return {54 query: "erpnext.accounts.doctype.journal_voucher.journal_voucher.get_against_jv",55 filters: { account: jvd.account }56 };57 });58 },59 setup_balance_formatter: function() {60 var df = frappe.meta.get_docfield("Journal Voucher Detail", "balance", this.frm.doc.name);61 df.formatter = function(value, df, options, doc) {62 var currency = frappe.meta.get_field_currency(df, doc);63 var dr_or_cr = value ? ('<label>' + (value > 0.0 ? __("Dr") : __("Cr")) + '</label>') : "";64 return "<div style='text-align: right'>"65 + ((value==null || value==="") ? "" : format_currency(Math.abs(value), currency))66 + " " + dr_or_cr67 + "</div>";68 }69 },70 against_voucher: function(doc, cdt, cdn) {71 var d = frappe.get_doc(cdt, cdn);72 if (d.against_voucher && !flt(d.debit)) {73 this.get_outstanding({74 'doctype': 'Purchase Invoice',75 'docname': d.against_voucher76 }, d)77 }78 },79 against_invoice: function(doc, cdt, cdn) {80 var d = frappe.get_doc(cdt, cdn);81 if (d.against_invoice && !flt(d.credit)) {82 this.get_outstanding({83 'doctype': 'Sales Invoice',84 'docname': d.against_invoice85 }, d)86 }87 },88 against_jv: function(doc, cdt, cdn) {89 var d = frappe.get_doc(cdt, cdn);90 if (d.against_jv && !flt(d.credit) && !flt(d.debit)) {91 this.get_outstanding({92 'doctype': 'Journal Voucher',93 'docname': d.against_jv,94 'account': d.account95 }, d)96 }97 },98 get_outstanding: function(args, child) {99 var me = this;100 return this.frm.call({101 child: child,102 method: "get_outstanding",103 args: { args: args},...
bom.js
Source:bom.js
...48cur_frm.add_fetch("item", "description", "description");49cur_frm.add_fetch("item", "stock_uom", "uom");50cur_frm.cscript.workstation = function(doc,dt,dn) {51 var d = locals[dt][dn];52 frappe.model.with_doc("Workstation", d.workstation, function(name, r) {53 d.hour_rate = r.docs[0].hour_rate;54 refresh_field("hour_rate", dn, "bom_operations");55 erpnext.bom.calculate_op_cost(doc);56 erpnext.bom.calculate_total(doc);57 });58}59cur_frm.cscript.hour_rate = function(doc, dt, dn) {60 erpnext.bom.calculate_op_cost(doc);61 erpnext.bom.calculate_total(doc);62}63cur_frm.cscript.time_in_mins = cur_frm.cscript.hour_rate;64cur_frm.cscript.fixed_cycle_cost = cur_frm.cscript.hour_rate;65cur_frm.cscript.item_code = function(doc, cdt, cdn) {66 get_bom_material_detail(doc, cdt, cdn);...
salary_slip.js
Source:salary_slip.js
1// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors2// License: GNU General Public License v3. See license.txt3cur_frm.add_fetch('employee', 'company', 'company');4// On load5// -------------------------------------------------------------------6cur_frm.cscript.onload = function(doc,dt,dn){7 if((cint(doc.__islocal) == 1) && !doc.amended_from){8 if(!doc.month) {9 var today=new Date();10 month = (today.getMonth()+01).toString();11 if(month.length>1) doc.month = month;12 else doc.month = '0'+month;13 }14 if(!doc.fiscal_year) doc.fiscal_year = sys_defaults['fiscal_year'];15 refresh_many(['month', 'fiscal_year']);16 }17}18// Get leave details19//---------------------------------------------------------------------20cur_frm.cscript.fiscal_year = function(doc,dt,dn){21 return $c_obj(doc, 'get_emp_and_leave_details','',function(r, rt) {22 var doc = locals[dt][dn];23 cur_frm.refresh();24 calculate_all(doc, dt, dn);25 });26}27cur_frm.cscript.month = cur_frm.cscript.employee = cur_frm.cscript.fiscal_year;28cur_frm.cscript.leave_without_pay = function(doc,dt,dn){29 if (doc.employee && doc.fiscal_year && doc.month) {30 return $c_obj(doc, 'get_leave_details',doc.leave_without_pay,function(r, rt) {31 var doc = locals[dt][dn];32 cur_frm.refresh();33 calculate_all(doc, dt, dn);34 });35 }36}37var calculate_all = function(doc, dt, dn) {38 calculate_earning_total(doc, dt, dn);39 calculate_ded_total(doc, dt, dn);40 calculate_net_pay(doc, dt, dn);41}42cur_frm.cscript.e_modified_amount = function(doc,dt,dn){43 calculate_earning_total(doc, dt, dn);44 calculate_net_pay(doc, dt, dn);45}46cur_frm.cscript.e_depends_on_lwp = cur_frm.cscript.e_modified_amount;47// Trigger on earning modified amount and depends on lwp48// ------------------------------------------------------------------------49cur_frm.cscript.d_modified_amount = function(doc,dt,dn){50 calculate_ded_total(doc, dt, dn);51 calculate_net_pay(doc, dt, dn);52}53cur_frm.cscript.d_depends_on_lwp = cur_frm.cscript.d_modified_amount;54// Calculate earning total55// ------------------------------------------------------------------------56var calculate_earning_total = function(doc, dt, dn) {57 var tbl = doc.earning_details || [];58 var total_earn = 0;59 for(var i = 0; i < tbl.length; i++){60 if(cint(tbl[i].e_depends_on_lwp) == 1) {61 tbl[i].e_modified_amount = Math.round(tbl[i].e_amount)*(flt(doc.payment_days)/cint(doc.total_days_in_month)*100)/100; 62 refresh_field('e_modified_amount', tbl[i].name, 'earning_details');63 }64 total_earn += flt(tbl[i].e_modified_amount);65 }66 doc.gross_pay = total_earn + flt(doc.arrear_amount) + flt(doc.leave_encashment_amount);67 refresh_many(['e_modified_amount', 'gross_pay']);68}69// Calculate deduction total70// ------------------------------------------------------------------------71var calculate_ded_total = function(doc, dt, dn) {72 var tbl = doc.deduction_details || [];73 var total_ded = 0;74 for(var i = 0; i < tbl.length; i++){75 if(cint(tbl[i].d_depends_on_lwp) == 1) {76 tbl[i].d_modified_amount = Math.round(tbl[i].d_amount)*(flt(doc.payment_days)/cint(doc.total_days_in_month)*100)/100;77 refresh_field('d_modified_amount', tbl[i].name, 'deduction_details');78 }79 total_ded += flt(tbl[i].d_modified_amount);80 }81 doc.total_deduction = total_ded;82 refresh_field('total_deduction'); 83}84// Calculate net payable amount85// ------------------------------------------------------------------------86var calculate_net_pay = function(doc, dt, dn) {87 doc.net_pay = flt(doc.gross_pay) - flt(doc.total_deduction);88 doc.rounded_total = Math.round(doc.net_pay);89 refresh_many(['net_pay', 'rounded_total']);90}91// trigger on arrear92// ------------------------------------------------------------------------93cur_frm.cscript.arrear_amount = function(doc,dt,dn){94 calculate_earning_total(doc, dt, dn);95 calculate_net_pay(doc, dt, dn);96}97// trigger on encashed amount98// ------------------------------------------------------------------------99cur_frm.cscript.leave_encashment_amount = cur_frm.cscript.arrear_amount;100// validate101// ------------------------------------------------------------------------102cur_frm.cscript.validate = function(doc, dt, dn) {103 calculate_all(doc, dt, dn);104}105cur_frm.fields_dict.employee.get_query = function(doc,cdt,cdn) {106 return{107 query: "erpnext.controllers.queries.employee_query"108 } ...
leave_application.js
Source:leave_application.js
1// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors2// License: GNU General Public License v3. See license.txt3cur_frm.add_fetch('employee','employee_name','employee_name');4cur_frm.cscript.onload = function(doc, dt, dn) {5 if(!doc.posting_date)6 set_multiple(dt,dn,{posting_date:get_today()});7 if(doc.__islocal) {8 cur_frm.set_value("status", "Open");9 cur_frm.cscript.calculate_total_days(doc, dt, dn);10 }11 cur_frm.set_query("leave_approver", function() {12 return {13 filters: [["UserRole", "role", "=", "Leave Approver"]]14 };15 });16 cur_frm.cscript.get_leave_balance(cur_frm.doc);17}18cur_frm.cscript.refresh = function(doc, dt, dn) {19 if(doc.__islocal) {20 cur_frm.set_value("status", "Open")21 }22 cur_frm.set_intro("");23 if(doc.__islocal && !in_list(user_roles, "HR User")) {24 cur_frm.set_intro(__("Fill the form and save it"))25 } else {26 if(doc.docstatus==0 && doc.status=="Open") {27 if(user==doc.leave_approver) {28 cur_frm.set_intro(__("You are the Leave Approver for this record. Please Update the 'Status' and Save"));29 cur_frm.toggle_enable("status", true);30 } else {31 cur_frm.set_intro(__("This Leave Application is pending approval. Only the Leave Approver can update status."))32 cur_frm.toggle_enable("status", false);33 if(!doc.__islocal) {34 cur_frm.frm_head.appframe.set_title_right("");35 }36 }37 } else {38 if(doc.status=="Approved") {39 cur_frm.set_intro(__("Leave application has been approved."));40 if(cur_frm.doc.docstatus==0) {41 cur_frm.set_intro(__("Please submit to update Leave Balance."));42 }43 } else if(doc.status=="Rejected") {44 cur_frm.set_intro(__("Leave application has been rejected."));45 }46 }47 }48}49cur_frm.cscript.employee = function (doc, dt, dn){50 cur_frm.cscript.get_leave_balance(doc, dt, dn);51}52cur_frm.cscript.fiscal_year = function (doc, dt, dn){53 cur_frm.cscript.get_leave_balance(doc, dt, dn);54}55cur_frm.cscript.leave_type = function (doc, dt, dn){56 cur_frm.cscript.get_leave_balance(doc, dt, dn);57}58cur_frm.cscript.half_day = function(doc, dt, dn) {59 if(doc.from_date) {60 set_multiple(dt,dn,{to_date:doc.from_date});61 cur_frm.cscript.calculate_total_days(doc, dt, dn);62 }63}64cur_frm.cscript.from_date = function(doc, dt, dn) {65 if(cint(doc.half_day) == 1){66 set_multiple(dt,dn,{to_date:doc.from_date});67 }68 cur_frm.cscript.calculate_total_days(doc, dt, dn);69}70cur_frm.cscript.to_date = function(doc, dt, dn) {71 if(cint(doc.half_day) == 1 && cstr(doc.from_date) && doc.from_date != doc.to_date){72 msgprint(__("To Date should be same as From Date for Half Day leave"));73 set_multiple(dt,dn,{to_date:doc.from_date});74 }75 cur_frm.cscript.calculate_total_days(doc, dt, dn);76}77cur_frm.cscript.get_leave_balance = function(doc, dt, dn) {78 if(doc.docstatus==0 && doc.employee && doc.leave_type && doc.fiscal_year) {79 return cur_frm.call({80 method: "get_leave_balance",81 args: {82 employee: doc.employee,83 fiscal_year: doc.fiscal_year,84 leave_type: doc.leave_type85 }86 });87 }88}89cur_frm.cscript.calculate_total_days = function(doc, dt, dn) {90 if(doc.from_date && doc.to_date){91 if(cint(doc.half_day) == 1) set_multiple(dt,dn,{total_leave_days:0.5});92 else{93 // server call is done to include holidays in leave days calculations94 return frappe.call({95 method: 'erpnext.hr.doctype.leave_application.leave_application.get_total_leave_days',96 args: {leave_app: doc},97 callback: function(response) {98 if (response && response.message) {99 cur_frm.set_value('total_leave_days', response.message.total_leave_days);100 }101 }102 });103 }104 }105}106cur_frm.fields_dict.employee.get_query = erpnext.queries.employee;107frappe.ui.form.on("Leave Application", "leave_approver", function(frm) {108 frappe.call({109 "method": "frappe.client.get",110 args: {111 doctype: "User",112 name: frm.doc.leave_approver113 },114 callback: function (data) {115 frappe.model.set_value(frm.doctype, frm.docname, "leave_approver_name",116 data.message.first_name117 + (data.message.last_name ? (" " + data.message.last_name) : ""))118 }119 })...
map.js
Source:map.js
1function(doc) {2//chw_dashboard3//returns an array of key: chw_username: [count, last_pact_id, last_xmlns, received_on]4 function bw_array_sort(a, b) {5 //doing reverse date order6 var datea = parse_date(a['test_date']);7 var dateb = parse_date(b['test_date']);8 if (datea > dateb) {9 return -1;10 } else if (datea < dateb) {11 return 1;12 } else {13 return 0;14 }15 }16 function get_encounter_date(xform_doc) {17 function get_date_string(xform_doc) {18 // check some expected places for a date19 if (xform_doc.encounter_date) return xform_doc.encounter_date;20 if (xform_doc.note && xform_doc.note.encounter_date) return xform_doc.note.encounter_date;21 if (xform_doc.Meta && xform_doc.Meta.TimeEnd) return xform_doc.Meta.TimeEnd;22 if (xform_doc.Meta && xform_doc.Meta.TimeStart) return xform_doc.Meta.TimeStart;23 return null;24 }25 return parse_date(get_date_string(xform_doc));26 }27 function get_user_id(xform_doc) {28 if (xform_doc.Meta && xform_doc.Meta.username) return xform_doc.Meta.username;29 if (xform_doc.Meta && xform_doc.Meta.chw_id) return xform_doc.Meta.chw_id;30 }31 //Parse the encounter date string.32 //note, that the dates are in 1 indexed months, so NO additions here.33 function parse_date(date_string) {34 if (!date_string) return new Date(1970, 1, 1);35 // hat tip: http://stackoverflow.com/questions/2587345/javascript-date-parse36 var parts = date_string.match(/(\d+)/g);37 // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])38 return new Date(parts[0], parts[1] - 1, parts[2]); // months are 0-based39 }40 if (doc.doc_type == "XFormInstance" && doc.xmlns != "http://code.javarosa.org/devicereport") {41 //map 1: XForm Information regarding bloodwork and submission counts42 if (doc.form.encounter_date) {43 var edate = parse_date(doc.form.encounter_date);44 } else if (doc.form.note && doc.form.note.encounter_date) {45 var edate = parse_date(doc.form.note.encounter_date);46 }47 //return it in regular months, not zero indexed.48 if (doc.form.pact_id) {49 var pact_id = doc.form.pact_id;50 } else if (doc.form.note && doc.form.note.pact_id) {51 var pact_id = doc.form.note.pact_id;52 }53 var ret_dict = {};54 ret_dict['count'] = 1;55 ret_dict['encounter_date'] = get_encounter_date(doc.form);56 ret_dict['doc_id'] = doc._id;57 ret_dict['pact_id'] = pact_id;58 ret_dict['last_xmlns'] = doc.xmlns;59 ret_dict['last_received'] = doc.received_on;60 emit(get_user_id(doc.form), ret_dict);61 }...
Using AI Code Generation
1var imposter = {2 {3 {4 "is": {5 }6 }7 }8};9var mb = require('mountebank');10mb.create(imposter)11 .then(function (imposter) {12 })13 .catch(function (error) {14 console.error(error);15 });
Using AI Code Generation
1var mb = require('mountebank');2var imposter = {3 {4 {5 is: {6 }7 }8 }9};10mb.create(imposter).then(function (imposter) {11 imposter.stop();12});13var mb = require('mountebank');14var imposter = {15 {16 {17 is: {18 }19 }20 }21};22mb.create(imposter).then(function (imposter) {23 imposter.stop();24});
Using AI Code Generation
1var mb = require('mountebank');2var imposter = { port: 80, protocol: 'http', stubs: [{ responses: [{ is: { body: 'Hello World!' } }] }] };3mb.create(imposter, function (error) {4 if (error) {5 console.log('Error creating imposter: ' + error.message);6 } else {7 console.log('Imposter created');8 }9});
Using AI Code Generation
1var mb = require('mountebank');2var port = 2525;3var protocol = 'http';4var host = 'localhost';5var path = '/test';6var stub = {7 {8 is: {9 headers: {10 },11 }12 }13};14mb.create(port, protocol, host, path, stub)15 .then(function (imposter) {16 console.log('Imposter created on port ' + imposter.port);17 })18 .catch(function (error) {19 console.error('Error creating imposter', error);20 });21var mb = require('mountebank');22var port = 2525;23var protocol = 'http';24var host = 'localhost';25var path = '/test';26var stub = {27 {28 is: {29 headers: {30 },31 }32 }33};34mb.create(port, protocol, host, path, stub)35 .then(function (imposter) {36 console.log('Imposter created on port ' + imposter.port);37 })38 .catch(function (error) {39 console.error('Error creating imposter', error);40 });41var mb = require('mountebank');42var port = 2525;43var protocol = 'http';44var host = 'localhost';45var path = '/test';46var stub = {47 {48 is: {49 headers: {50 },51 }52 }53};54mb.create(port, protocol, host, path, stub)55 .then(function (imposter) {56 console.log('Imposter created on port ' + imposter.port);57 })58 .catch(function (error) {59 console.error('Error creating imposter', error);60 });61var mb = require('mountebank');62var port = 2525;
Using AI Code Generation
1var mb = require('mountebank');2var imposter = mb.create({port: 2525, protocol: 'http'});3imposter.post('/test', function (request, response) {4 response.send(200, 'Hello World!');5});6imposter.start();7var mb = require('mountebank');8var imposter = mb.create({port: 2525, protocol: 'http'});9imposter.post('/test', function (request, response) {10 response.send(200, 'Hello World!');11});12imposter.start();13var mb = require('mountebank');14var imposter = mb.create({port: 2525, protocol: 'http'});15imposter.post('/test', function (request, response) {16 response.send(200, 'Hello World!');17});18imposter.start();19var mb = require('mountebank');20var imposter = mb.create({port: 2525, protocol: 'http'});21imposter.post('/test', function (request, response) {22 response.send(200, 'Hello World!');23});24imposter.start();25var mb = require('mountebank');26var imposter = mb.create({port: 2525, protocol: 'http'});27imposter.post('/test', function (request, response) {28 response.send(200, 'Hello World!');29});30imposter.start();31var mb = require('mountebank');32var imposter = mb.create({port: 2525, protocol: 'http'});33imposter.post('/test', function (request, response) {34 response.send(200, 'Hello World!');35});36imposter.start();37var mb = require('mountebank');38var imposter = mb.create({port: 2525, protocol: 'http'});39imposter.post('/test', function (request, response) {40 response.send(200, 'Hello World!');41});42imposter.start();43var mb = require('mountebank');44var imposter = mb.create({port: 2525, protocol: 'http'});45imposter.post('/test', function (request, response) {46 response.send(200, 'Hello World!');
Using AI Code Generation
1var mb = require('mountebank'),2 assert = require('assert'),3 response = {status: 200, headers: {'Content-Type': 'text/plain'}, body: 'Hello World!'};4mb.create({port: port}, function (error, mbServer) {5 assert.ifError(error);6 mbServer.post('/imposters', {protocol: protocol, port: port, stubs: [{responses: [response]}]}, function (error, response) {7 assert.ifError(error);8 assert.strictEqual(response.statusCode, 201);9 mbServer.get('/imposters/2525', function (error, response) {10 assert.ifError(error);11 assert.strictEqual(response.statusCode, 200);12 assert.deepEqual(response.body, {port: port, protocol: protocol, stubs: [{responses: [response]}]});13 mbServer.del('/imposters', function (error, response) {14 assert.ifError(error);15 assert.strictEqual(response.statusCode, 200);16 mbServer.close();17 });18 });19 });20});
Using AI Code Generation
1const mb = require('mountebank');2const port = 2525;3const imposterPort = 4545;4const imposterName = 'imposter';5const imposterProtocol = 'http';6const imposterStub = {7 {8 is: {9 }10 }11};12const imposterPredicate = {13 equals: {14 }15};16const imposterStub = {17 {18 is: {19 }20 }21};22const imposterPredicate = {23 equals: {24 }25};26const imposterStub = {27 {28 is: {29 }30 }31};32const imposterPredicate = {33 equals: {34 }35};36const imposterStub = {37 {38 is: {39 }40 }41};42const imposterPredicate = {43 equals: {44 }45};46const imposterStub = {47 {48 is: {49 }50 }51};52const imposterPredicate = {53 equals: {54 }55};56const imposterStub = {57 {58 is: {59 }60 }61};62const imposterPredicate = {63 equals: {64 }65};66const imposterStub = {67 {68 is: {69 }70 }71};72const imposterPredicate = {73 equals: {74 }75};76const imposterStub = {77 {78 is: {79 }80 }81};82const imposterPredicate = {83 equals: {84 }85};86const imposterStub = {
Using AI Code Generation
1var imposter = require('mountebank').create();2var port = 2525;3var doc = imposter.doc(port);4console.log(doc);5var imposter = require('mountebank').create();6var port = 2525;7 {8 {9 {10 is: {11 }12 }13 }14 }15];16imposter.post(imposters, function () {17 console.log('imposter running on port ' + port);18});19var imposter = require('mountebank').create();20var port = 2525;21imposter.delete(port, function () {22 console.log('imposter deleted on port ' + port);23});24var imposter = require('mountebank').create();25var port = 2525;26 {27 {28 {29 is: {30 }31 }32 }33 }34];35imposter.put(imposters, function () {36 console.log('imposter running on port ' + port);37});38var imposter = require('mountebank').create();39var port = 2525;40imposter.get(port, function (error, imposters) {41 console.log('imposter running on port ' + port);42 console.log(imposters);43});44var imposter = require('mountebank').create();45imposter.reset(function () {46 console.log('all imposters deleted');47});48var imposter = require('mountebank').create();49var port = 2525;50var stub = {51 {52 is: {
Using AI Code Generation
1var mb = require('../../mountebank/lib/mountebank');2var port = 2525;3var protocol = 'http';4var host = 'localhost';5var path = '/test';6var method = 'GET';7var stubs = [{8 predicates: [{9 equals: {10 }11 }],12 responses: [{13 is: {14 }15 }]16}];17var imposters = [{18}];19var options = {20};21mb.create(options)22 .then(function (imposter) {23 console.log('Imposter created at ' + imposter.url);24 })25 .catch(function (error) {26 console.error(error);27 });28var mb = require('../../mountebank/lib/mountebank');29var port = 2525;30var protocol = 'http';31var host = 'localhost';32var path = '/test';33var method = 'GET';34var stubs = [{35 predicates: [{36 equals: {37 }38 }],39 responses: [{40 is: {41 }42 }]43}];44var imposters = [{45}];46var options = {47};48mb.create(options)49 .then(function (imposter) {50 console.log('Imposter created at ' + imposter.url);51 })52 .catch(function (error) {53 console.error(error);54 });55var mb = require('../../mountebank/lib/mountebank');56var port = 2525;57var protocol = 'http';58var host = 'localhost';59var path = '/test';60var method = 'GET';
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!!