This repository has been archived by the owner on Jan 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsearch.html
1188 lines (963 loc) · 546 KB
/
search.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<title>Test Armada</title>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/common.css">
<link rel="stylesheet" type="text/css" href="/css/subheader.css">
<link rel="stylesheet" type="text/css" href="/css/header.css">
<link rel="stylesheet" type="text/css" href="/css/home.css">
<link rel="stylesheet" type="text/css" href="/css/doc.css">
<link rel="stylesheet" type="text/css" href="/css/training.css">
<link rel="stylesheet" type="text/css" href="/css/faq.css">
<link rel="stylesheet" type="text/css" href="/css/contact.css">
<link rel="stylesheet" type="text/css" href="/css/search.css">
<link rel="stylesheet" type="text/css" href="/css/custom.css">
<link rel="stylesheet" type="text/css" href="/css/slick.css">
<link rel="stylesheet" type="text/css" href="/css/prism.css">
<link rel="stylesheet" type="text/css" href="/css/responsive.css">
<link rel="shortcut icon" href="/documentation/images/favicon.ico">
</head>
<body>
<div class="subheader">
<div class="search-bar">
<form class="search-bar__form" action="/search" method="get">
<div class="select-box-sub">
<select class="select-box-sub__select" name="fleet" id="fleet-box" onchange="document.getElementById('search-box').focus();">
<option value="all">All Fleets</option>
<option value="Functional Testing">Functional Testing</option>
<option value="Mocking">Mocking</option>
<option value="Performance Testing">Performance Testing</option>
<option value="Data Insights">Data Insights</option>
</select>
</div>
<input type="text" id="search-box" name="query" autocomplete="off" class="search-box-sub">
</form>
</div>
<div class="nav-sub-links">
<a href="/documentation/Presentations" class="nav-sub-links__link">Presentations</a>
<a href="/documentation/About" class="nav-sub-links__link">About Us</a>
<a href="https://github.com/TestArmada/" class="nav-sub-links__link" target="_blank">GitHub</a>
</div>
</div>
<header>
<a href="/">
<img src="/documentation/images/ta-logo.png" class="logo" alt="Main Brand Logo"
srcset="/documentation/images/ta-logo%402x.png 2x, /documentation/images/ta-logo%403x.png 3x">
</a>
<!-- <form action="/search" method="get">
<input type="text" id="search-box" name="query" placeholder="Search" class="search-box">
<div class="select-box">
<select name="fleet" id="fleet-box" onchange="document.getElementById('search-box').focus();">
<option value="all">All Fleets</option>
<option value="Functional Testing">Functional Testing</option>
<option value="Mocking">Mocking</option>
<option value="Performance Testing">Performance Testing</option>
<option value="Data Insights">Data Insights</option>
</select>
</div>
</form> -->
<div class="nav-links">
<div class="nav-links__fleets">
<a class="nav-links__fleets-btn">
Fleets <img src="/images/arrow-down-icon.png" class="arrow-down-icon"
srcset="/images/arrow-down-icon%402x.png 2x,
/images/arrow-down-icon%403x.png 3x">
</a>
<div class="nav-links__fleets-content">
<a href="/">
All Fleets
</a>
<a href="/documentation/Functional Testing/">
Functional Testing
</a>
<a href="/documentation/Mocking/">
Mocking
</a>
<a href="/documentation/Performance Testing/">
Performance Testing
</a>
<a href="/documentation/Data Insights/">
Data Insights
</a>
</div>
</div>
<a href="/faq" class="nav-links__main-links">FAQ</a>
</div>
</header>
<div class="container">
<div class="inner-container">
<div class="breadcrumb">
<p>
<a class="breadcrumb__link" href="/">Home</a>
<img src="/images/arrow-right-icon.png" srcset="/images/[email protected] 2x,
/images/[email protected] 3x" class="arrow-right-icon">
<span class="breadcrumb__current-page">Search Results</span>
</p>
</div>
<div class="search-content">
<h2 id="result-count">Searching...</h2>
<p id="not-found-message">This means that we either couldn't find a match for your searched query in our documentation or it's a very common term that returned too many results. Please refine your search query and try again.</p>
<div id="search-results"></div>
<div id="pagination" class="pagination"></div>
</div>
</div>
<script>
window.store = {
"documentation-performance-testing": {
"title": "Performance Testing",
"content": " Home Performance Testing Performance Testing Execute performance tests for both Client ( web & mobile web ) and Web Service applications, with options to run on CI pipeline or any internal/external environments. Coming Soon rWeb Performance testing for Web and mobile Web DECLARATIVE Coming Soon Services Performance testing for backend Web Services DECLARATIVE ",
"url": "/documentation/Performance Testing/"
},
"documentation-mocking": {
"title": "Mocking",
"content": " Home Mocking Mocking Create reliable test data for test execution and development. “Mocks” are imitations that emulate real software components for testing purposes. Mocking functions focus on very specific scenarios and contexts and simulate behavioral responses to fulfill a certain development need for repeated and reliable test execution and debugging. rWeb Create mocks for Web and mWeb JAVASCRIPT Services Create mocks for dependent services JAVASCRIPT Native Android Create mocks for Android JAVASCRIPT Native iOS Create mocks for iOS JAVASCRIPT ",
"url": "/documentation/Mocking/"
},
"documentation-functional-testing": {
"title": "Functional Testing",
"content": " Home Functional Testing Functional Testing Run web, native or web services functional tests reliably at massive parallel scale, By distributing tests across available CPU cores, Test Armada blazes through long test suites in a fraction of the time, aggregating results in one friendly report. rWeb Functional testing for rWeb JAVASCRIPT Native Android Functional testing for Android JAVASCRIPT Native iOS Functional testing for iOS JAVASCRIPT ",
"url": "/documentation/Functional Testing/"
},
"documentation-data-insights": {
"title": "Data Insights",
"content": " Home Data Insights Data Insights The data insights platform collates test run data from multiple sources, providing a single source of truth for deep insight in to code quality, cross-browser test results and application performance. Coming Soon Functional Real time and Trending functional test reports Real Time Trending Coming Soon Performance Real time and Trending performance test reports Real Time Trending ",
"url": "/documentation/Data Insights/"
},
"documentation-presentations": {
"title": "Presentations",
"content": " Home Presentations PresentationsSauce Labs at Walmart Labs with Test Armada ",
"url": "/documentation/Presentations"
},
"documentation-about": {
"title": "About",
"content": " Home About About UsTest Armada is a technology agnostic quality automation platform to enable engineers to develop and deliver high quality software.Our TeamClaude Jones, Sr. Director of Engineering - [email protected] Verma, Sr. Engineering Manager - [email protected] Testing FleetRenas Reda, Staff Engineer - [email protected] Zhu, Staff Engineer - [email protected] Jia, Software Engineer - [email protected] Ahrens, Staff Engineer - [email protected] Wang, Staff Engineer - [email protected] FleetHimanshu Jain, Sr. Engineering Manager - [email protected] Parikh, Senior Engineer - [email protected] Chapman, Staff Engineer - [email protected] Shah, Software Engineer - [email protected] Testing FleetPraveen Kulkarni, Sr. Engineering Manager - [email protected] Oks, Staff Engineer - [email protected] Gupta, Senior Engineer - [email protected] Shah, Senior Engineer - [email protected] RabbanSab, Senior Engineer - [email protected] Maharana, Software Engineer - [email protected] Bouchard, Senior Engineer [email protected] Insights FleetDave Stevens, Sr. Engineering Manager - [email protected] Giri, Staff Engineer - [email protected] Davis, Staff Engineer - [email protected] Pullepu - Software Engineer - [email protected] Lichtenfeld, Principle Engineer - [email protected] Parkhi, Principal Program Manager - [email protected] Kirn, Program Manager - [email protected] ",
"url": "/documentation/About"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-401-state": {
"title": "State",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. What is state?State allows you to maintain state of your server, for example if a user is logged in or logged out. The mock server internally uses Hapi node server, which helps you return the state of the current application state. Within any response handler, use this.state('varName') to access an object stored in the state and this.state('varName', 'varValue') where varValue can be any type of object you want to set the state.2. How to set a state in mock server?midway.route({ path: '/api/login', label: 'LogIn', method: 'POST', handler: function(request, reply) { // now you can use this.state('loggedIn') in any route handler to see if the user has logged in this.state('loggedIn', true); reply().code(204); }});",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 401/State"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-401-starting-https-server-with-mock-server": {
"title": "Starting HTTPS server with Mock Server",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. Updating run-mock-server-console.js to enable HTTPSrequire('./endpoints');var fs = require('fs');var midway = require('testarmada-midway'); midway.start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, httpsPort: 4444, project: 'HelloMidway'});The default port for HTTPS is 44442. Starting mock server with HTTPS enabledOnce you add the above code, the mock server will provide the HTTPS and HTTPS support by default. Hence when the mock server starts up, you will see both the ports open. Note that the mock server auto generates the certificates (key.pem and cert.pem). If you want to provide your own key and certificate, you can provide it under the mocked data directory.",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 401/Starting HTTPS server with Mock Server"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-401-rest-apis": {
"title": "Rest APIs",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. Set VariantMethod : POSTSyntax : {host}:{port}/_admin/api/route/{routeId}Rest API : curl -H "Content-Type: application/json" -X POST -d '{"variant":"preorder"}' http://localhost:8000/_admin/api/route/getCollection?returnConfig=truemidway.route({ id: 'getCollection', label: 'Get Collection', path: '/product/grouping/api/collection/{collectionId}', variantLabel: 'default', handler: function(req, reply) { var response = getResponseData('/product/grouping/api/collection', 'default'); reply(response); }}).variant({ id: 'preorder', label: 'Get Pre-order Collection', handler: function (req, reply) { reply({message: 'hello pre-order'}); }});To get the config back as a response, add query parameter returnConfig=true as shown in example above2. Set Mock IdMethod : GETSyntax : {host}:{port}/_admin/api/midway/setMockId/{mockid}/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/setMockId/1234/default3. Get Mock IdMethod : GETSyntax : {host}:{port}/_admin/api/midway/getMockId/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/getMockId/default4. Reset Mock IdMethod : GETSyntax : {host}:{port}/_admin/api/midway/resetMockId/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/resetMockId/default5. Get Url CountMethod : GETSyntax : {host}:{port}/_admin/api/midway/getURLCount/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/getURLCount/default6. Reset Url CountMethod : GETSyntax : {host}:{port}/_admin/api/midway/resetURLCount/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/resetURLCount/default7. Re-set the state of Mock ServerMethod : POSTSyntax : {host}:{port}/_admin/api/state/resetRest API : curl -X POST http://localhost:8000/_admin/api/state/reset8. Register SessionMethod : GETSyntax : {host}:{port}/_admin/api/midway/registerSessionRest API : curl http://localhost:8000/_admin/api/midway/registerSession9. Get SessionsMethod : GETSyntax : {host}:{port}/_admin/api/midway/getSessionsRest API : curl http://localhost:8000/_admin/api/midway/getSessions10. Check SessionMethod : GETSyntax : {host}:{port}/_admin/api/midway/checkSession/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/checkSession/{sessionid}11. Close SessionMethod : GETSyntax : {host}:{port}/_admin/api/midway/closeSession/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/closeSession/{sessionid}",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 401/Rest APIs"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-401-mocking-utility-methods": {
"title": "Mocking Utility Methods",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. RespondWithFile Utilitymidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }})Setting Codemidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400}); }})Custom File Locationmidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json'}); }})Setting Headersmidway.route({id: 'message',label: 'hello message',path: '/message',handler: function(req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json', headers: myHeaders});}});Setting Cookiesmidway.route({id: 'message',label: 'hello message',path: '/message',handler: function(req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; var cookies = [ {name: 'com.wm.customer', value: 'vz7.0b5c56'}, {name: 'CID', value: 'SmockedCID', options: {domain: 'domain', path: '/'}}, {name: 'anotherCookie', value: 'cookieValue'} ]; midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json', headers: myHeaders, cookies: cookies});}});Setting Delaymidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; var cookies = [ {name: 'com.wm.customer', value: 'vz7.0b5c56'}, {name: 'CID', value: 'SmockedCID', options: {domain: 'domain', path: '/'}}, {name: 'anotherCookie', value: 'cookieValue'} ]; midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json', headers: myHeaders, cookies: cookies, delay: 1000}); }});Modifying Static JSON responseIf you have many variants for a REST end point and the mocked data for all variants can use the same JSON response with few changes to the values, than this feature is what you need. This feature allows you to dynamically change a JSON file before sending the response back from the mock server for the request. It removes the need of having one to one mapping of static JSON files with each variants.// Static Response JSON File{ "id": "1234", "name": "toothpaste", "details": [ { "flavor": "Mint 1", "Size": "10", "Size_Type": "ounce" }, { "flavor": "Mint", "Size": "10", "Size_Type": "ounce" } ]}// Sample code for substituting id from 1234 to 7777 and flavor from Mint to Mint 2 for second array element in routesmidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { var dataToChange = { 'id': '7777', 'details[1].flavor': 'Mint 2' } midway.util.respondWithFile(this, reply, {transpose: dataToChange}); }});// Dynamic Response JSON File returned from Mock service{ "id": "7777", "name": "toothpaste", "details": [ { "flavor": "Mint 1", "Size": "10", "Size_Type": "ounce" }, { "flavor": "Mint 2", "Size": "10", "Size_Type": "ounce" } ]}2. Logging utilityMidway exposes a logging utility which can be used to log datamidway.log.debug('This is debug Message');midway.log.info('This is info Message');midway.log.error('This is error Message');midway.log.warn('This is warn Message');midway.log.setLogLevel('debug');midway.log.getLogLevel();midway.log.resetLogLevel();// default level is INFO3. Responding with a specific variant in handlers (respondWithMockVariant)This function will respond with a variant on the main route handler. The variant passed in MUST be the variant on existing route.midway.util.respondWithMockVariant(this, 'variant', reply);The variant passed in MUST be the variant on existing route.midway.route({ id: 'respondWithVariant', label: 'Respond With Variant', path: '/respondWithVariant', variantLabel: 'Respond With Variant Main Route', handler: function (req, reply) { midway.util.respondWithMockVariant(this, 'variant', reply); // make sure that the variant exist in the same route. }}).variant({ id: 'variant', label: 'Respond With Variant Variant Route', handler: function (req, reply) { reply({'message': 'I am an example of respond_with_mock_variant instead of response of main route '}); }});4. GetUrlCountTo get URL count for all Rest APIs mocked by mock serverMidway API : midway.getURLCount("default");5. ResetUrlCountTo resets URL count to zeroMidway API : midway.resetURLCount("default");",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 401/Mocking Utility Methods"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-401-exercise": {
"title": "Exercise",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExerciseUpdate the previous mock server with the following:Add a logg-in route api/loginAdd a log-out route api/logoutAdd a state variable loggedIn and set true/false value based on the above APIs.Update the get/message default handler to return the message Hello: fname lname if user is logged in by reading from the query parameters otherwise Hello: Guest is the customer Id is less than equal to 5 characters.Update the get/message Hello Universe variant to modify the file to following using transpose data based on if user is logged in or logged out- User Logged In{ message: fname lname}- User Logged Out{ message: Guest}Start mock serverHit get/message with customer id length <=5 and see you should get Hello: GuestSet the variant to Hello UniverseHit get/message with customer id length <=5 and see you should get message: GuestHit api/loginSet the variant to defaultHit http://localhost:8000/get/message/12345?fname=John&lname=Doe with customer id length <=5 and see you should get Hello: John Doe.Set the variant to Hello UniverseHit http://localhost:8000/get/message/12345?fname=John&lname=Doe with customer id length <=5 and see you should get message:John DoeHit api/logout and repeat 5 to 7.Create and install certificates to enable HTTPS in Midway.Update run-mock-server-console.js to enable https in mock server.Start mock server and navigate to https://localhost:4444/_admin and repeat 5 to 12 steps.",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 401/Exercise"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-301-setmockid": {
"title": "SetMockId",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. What is SetMockIdThis feature is very handy when you want to stub all the endpoints for a particular test without manually writing the paths for those endpoints. Generally applicable in scenarios where one page calls different endpoints according to test flows. You do not need to set variant or create variants for these endpoints. You will need to manually store the stubbed JSON files in the file structure location which are specified by your endpoints. The endpoints responses can be captured and stored under mocked data directory as a one time setup.2. How SetMockId works?ScenarioLets say your test case requires to mock two end points /api/message and /api/product/getStatus. These endpoints are called three times each. For the first end point you always want to return the same data (in json) while for the second endpoint you want to return the same data for the first and third call (in html) and a different data for the second call (in html).ImplementationCreate a folder under the mocked-data of your test directory (this folder name is configurable when you start your mock server by passing mockedDirectory option) by the name test1. Under this folder add the following files for your mocked response.api-message-GET.json - This will be returned for all the calls for the first endpoint with default response code 200api-product-getStatus-GET.html - This will be returned for all the calls for the second endpoint with default response code 200, except for the second and third call as it has its own fileapi-product-getStatus-GET-2.html - This will be returned for the second call for the second endpoint with default response code 200api-product-getStatus-GET-3-code-201.html - This will be returned for the third call for the second endpoint with response code 201Now set the setMockId either by mock api, UI or rest call to set to test1ExplanationThe underlying mock service automatically figures out the file extension so that you do not have to specify it. If you have the same file with multiple file extension than the following order is used:JSONHTMLTXTFirst file encountered of any other extensionOnce the midway.setMockId(“test1”) API is called, Midway only looks for the responses under the test1 folder. If it does not find the response, it will return 404 with the file name that it did not find. Midway internally keeps track of the number of times each individual endpoint is called after client.setMockId(“test1”) API is called and first looks for the file with count specific name such as api-message-GET-1.json, if it does not find the said file then it looks for the default file which is api-message-GET.json.3. Good To KnowIf setMockId is set, then custom file path in handlermidway.util.respondWithFile(this, reply, {filePath: ‘./message/GET/default.json’});and file based on URL path ./mocked-data/api/message/get/default.json are ignored for the mocked response. Here is the order followed for file lookup:SetMockIdCustom File Path for default or variants endpoints.File based on URL Path for default or variants endpoints.SetMockId does not work with in-line Handlermidway.route({ id: 'message', label: 'Message', path: '/get/message/{customerid}', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { var lname = req.query.lname; var fname = req.query.fname; var customerid = req.params.customerid; if (customerid.length > 5) { reply().code(400); } else { reply('Hello ' + fname + " " + lname); } }})",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 301/SetMockId"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-301-parallel-sessions": {
"title": "Parallel Sessions",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. What is parallel sessions and why it's needed?Parallel sessions allows you to run multiple instance of server virtually while running only one server. This is helpful when you are running multiple test cases which access the same routes but different variants as parallel sessions allow you to set different variants on same routes without conflicting. This saves CPU and RAM both as only one server is running instead of multiple.2. How Parallel Sessions works internally?3. How to add parallel sessions?To add parallel sessions, modify run-mock-server-console.js to add 'sessions' parameter.require('./endpoints');var midway = require('testarmada-midway');midway.start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, sessions: 2, project: 'HelloMidway'});You can also start or add sessions via command line argumentnode resources/run-mock-server-console.js --midwaySessions 2If you pass sessions = 2, there will be two parallel sessions along with one default session.4. Supported APIs for Parallel sessionsRegister SessionTo register sessions to be usedvar sessionId = midway.registerSession();Get SessionsTo get all the active sessionsvar activeSessions = midway.getSessions();Check SessionTo check the session status (Available or In-Use or invalid)var sessionStatus = midway.checkSession(sessionId);Close SessionTo de-register session for later usevar closeSession = midway.closeSession(sessionId);5. Using Parallel SessionsTo use a parallel session call the following api:curl http://localhost:8000/_admin/api/midway/registerSessionormidway.registerSession()and a session id will be returned.Append this sessionId to the mocked host address to use this parallel session. For ex: If your mock host server is http://localhost:8080 and your session id is 112233 then the mock server address for this parallel session will be http://localhost:8080/112233.6. Verifying parallel sessionsStart mock server with two sessions. Now go to the 'Message' route. You will see three routes for message, default and two for parallel sessions that you just added. Now for each route choose a different variant and hit the URL icon. You will see that each time you will get a different value though you are hitting the same route.7. Understanding the Midway UI with sessionsTry to go through Midway UI to understand sessions.",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 301/Parallel Sessions"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-301-exercise": {
"title": "Exercise",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExerciseUpdate the previous mock server with the following:Update the Hello World variant of 'get/message' request toRemove the header parametersReturn the file as before by using RespondWithFile without handlerUpdate the default handler to return ONLY code 400 if the customer id is greater than 5 charactersStart mock server and test Step 1Now add data for setMockId for /get/message and /get/number routes.Return the following for URL hit count 1/get/message{ "message" : 1}/get/number{ "number" : 1}Return the following for URL hit count 2/get/message{ "message" : 2}/get/number{ "number" : 2}Return the following for default/get/message{ "message" : "Undefined"}/get/number{ "number" : "Undefined"}Call API to setMockId to the folder name via Midway UIHit the rest endpoint /get/message and /get/number one time each and verify the response is "message" : 1 and "number" : 1 respectively.Hit the rest endpoint /get/message and /get/number once more and verify the response for second hit is "message" : 2 and "number" : 2 respectively.Hit the rest endpoint /get/message and /get/number one more time to verify that the response is "message" : "undefined" and "number" : "undefined" respectively.Call ResetMockId API via Midway UIHit the rest endpoint /get/message and /get/number once each and verify the response is based on the handler and not on SetMockId - You may have to add appropriate file based on the route path.Update run-mock-server-console.js to add two parallel sessions to the server.Now call GetSessionId to register a session using Midway UI.Now set Hello World and Hello Universe variant for get/message api for the two sessions Ids respectively.Now hit the server https://localhost:8000/sessionId/get/message for different session Ids and verify that you get different responses as per each variant.",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 301/Exercise"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-301-different-ways-of-returning-response-data": {
"title": "Different ways of returning response data",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. Returning only the codemidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { reply().code(400); }})2. Using RespondWithFile without handlermidway.route({ path: '/api/customer/getId', label: 'Get Customer Id', method: 'GET', }).respondWithFile();3. Returning static mocked data with a response codemidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400}); }})",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 301/Different ways of returning response data"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-301-apis-for-setmockid": {
"title": "APIs for SetMockId",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. SetMockIdmidway.setMockId("1234", "default");2. GetMockIdmidway.getMockId("default");3. ResetMockIdmidway.resetMockId("default");",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 301/APIs for SetMockId"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-201-returning-response-from-a-file": {
"title": "Returning Response from a File",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. What does it mean?This feature allows you to respond with a data stored in a file instead of hard coding the response data in the routes definition. This way user does not have to change the response rather can just swap the file with different data.2. How it works?midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }});In the above setup, file needed for default route, which is /get/fromFile should be located at ./mocked-data/get/fromFile/GET/default.json3. What is mockedDirectory Path?Mocked directory path is the location to the base directory where all your mocked response file will be stored. This parameter is defined in run-mock-server-console.js file. It is defined at the start of mock server as shown in the code below:require('./endpoints-Midway-201');require('midway').start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, project: 'HelloMidway'});4. Automatic calculation of file locationThe path to the mocked data file is auto-calculated based on the route path. For variants, the name of the file should be changed from default to the variant name as shown below:midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }}).variant({ id: 'textData', label: 'Text Data', handler: function (req, reply) { midway.util.respondWithFile(this, reply); }})In the above example, mock server would look for ./resources/mocked-data/get/fromFile/GET/textData.txt file for the variant textData5. Providing custom path to the response fileA custom file path could also be provided for a mocked data file. to do so, use the following code:midway.route({ id: 'CustomResponseFile', label: 'Response From Custom Path', path: '/get/customFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {filePath: './custom.json'}); }})Midway will look for the file under MockedDirectory only but at ./resources/mocked-data/custom.json",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 201/Returning Response from a File"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-201-request-call-information": {
"title": "Request Call Information",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. Query ParametersLet's say you go to the following URL: http://localhost:8000/get/customerInfo/12345?ctype=new . To read the query parameter, do the following:var ctype = req.query.ctype;To run the above scenario, hit the following in any browser with Midway server running: http://localhost:8000/get/customerInfo/12345?ctype=new after updating the route tomidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { var id = req.params.customerid; var ctype = req.query.ctype; var replyString = 'Customer Type: ' + ctype + ' customer id: ' + id; reply(replyString); }});2. Header informationLet's say there is a header parameter 'name' with value 'John' is passed with the request. To read the testHeader parameter, do the following:var req = req.raw.req;var name = req.headers.name;To run the above scenario, use postman to make the following get call: http://localhost:8000/get/customerInfo/12345?ctype=new and add header 'name' with value 'John' after updating the route tomidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { var id = req.params.customerid; var ctype = req.query.ctype; var req = req.raw.req; var name = req.headers.name; var replyString = 'Customer Type: ' + ctype + ' customer id: ' + id + ' nameFromHeader: ' + name; reply(replyString); }});3. PayloadThe payload can be read using the following code://fname would be "Bob" if the posted body content (as JSON) was {"fname": "Bob"}var fname = req.payload.fname;To run the above scenario, use postman to make the following POST call: http://localhost:8000/payload and add payload {"fname": "Bob"} in the request.midway.route({ id: 'payload', label: 'Reading Payload', path: '/payload', method: 'POST', variantLabel: 'Payload', handler: function (req, reply) { var fname = req.payload.fname; reply(fname); }});4. Content TypesThe mock module is independent of content-types i.e. user can set any content type and mocking route is intercepted only based on the path defined in the mocked routes file.",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 201/Request Call Information"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-201-exercise": {
"title": "Exercise",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. Update the previous mock server with the followinga. Update the route /get/message to a dynamic URL which takes customer id as a parameter.b. Update the 'Hello World' variant to- return the following file with auto file location calculation.json { "message" : "Hello World" }- Set the following header params in response{ fname: John lname: Doe }Update the Hello Universe variantto return the following file and the file location should be hard coded.{ "message" : "Hello Universe"}Set the following cookie params in response{ customerId: 123456}Update the default handler to do the following:Add reading of query parameter 'fname' and 'lname' from the request.If the customer id is greater than 5 charactersreturn 'invalid id' as responseIf the customer id is less than or equal to 5 charactersreturn following response from the handler (NOT Using The File)Hello - fname lnameAdd a POST route /set/customerId and in default handler read the payload value and log it on console.{ "customerid": 123456}2. Start mock serverMake a REST call to /get/message with customer id greater than 5 characters and check the response is Invalid IdMake a REST call to /get/message with customer id equal to 5 characters and check the response to be Hello undefined undefinedMake a REST call to http://localhost:8000/get/message/12345?fname=John&lname=Doe and check the response to be Hello John DoeSwitch to Hello World variant and check the response is "message" : "Hello World" and use dev tools on Chrome browser to verify that the header params are set (fname: John and lname: Doe)Switch to Hello Universe variant and check the response is "message" : "Hello Universe" and use dev tools on Chrome browser to verify that the cookie is set (customerId: 123456)Make a post call to mock server at http://localhost:8000/set/customerId using Postman (or any other HTTP client) with the following data and verify that 12345 is logged on the console{ "customerId" : 12345}",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 201/Exercise"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-201-dynamic-urls": {
"title": "Dynamic URLs",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. How to create dynamic urls/get/customerInfo/{customerid}/{zipcode}2. Adding a dynamic URL in mock servermidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { reply('How to read the customer id :('); }});3. Reading dynamic URL parametersvar id = req.params.customerid;4. Using dynamic values to define responsemidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { var id = req.params.customerid; reply('Customer id is ' + id + ' :)'); }});5. Passing dynamic URL parameters from the Midway UITry to pass dynamic url parameters generated from Midway UI",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 201/Dynamic URLs"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-201-customizing-mocked-response": {
"title": "Customizing Mocked Response",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. Set custom headersmidway.route({ id: 'header', label: 'Custom Headers', path: '/set/headers', handler: function(req, reply) { reply({message: 'custom headers'}) .header('header1', 'test1') .header('header2', 'test2') .header('header3', 'test3') }}) midway.route({ id: 'header', label: 'Custom Headers', path: '/set/headers', handler: function (req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; midway.util.respondWithFile(this, reply, {headers: myHeaders}); }});2. Set custom cookiesmidway.route({ id: 'cookies', label: 'Custom Cookies', path: '/set/cookies', handler: function(req, reply) { reply({message: 'test'}) .state('cookie1', 'testCookie1') .state('cookie2', 'testCookie2') }}); midway.route({ id: 'cookies', label: 'Custom Cookies', path: '/set/cookies', handler: function (req, reply) { var cookies = [ {name: 'cookie1', value: 'testCookie1'}, {name: 'cookie2', value: 'testCookie2'}, ]; midway.util.respondWithFile(this, reply, {cookies: cookies}); }});3. Set CORS headersvar corsHeaders = { origin: ['*'], headers: ["Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"], credentials: true,} // Itemsmidway.route({ id: 'corsheaders', label: 'CORS', path: '/set/cors', config: { cors: corsHeaders }, handler: function(req, reply) { reply('cors headers set'); }});",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 201/Customizing Mocked Response"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-101-setting-and-installing-mock-server": {
"title": "Setting and Installing Mock Server",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. Pre-requisitesnode.js 4+ (npm is included in the package)2. Add mock dependency to package.json"dependencies": { "testarmada-midway": "^1.0.1"}3. Install mock dependency with npm installRun npm install command to install mock related dependencies.4. Add resources/endpoints.js and create ./resources/mocked-data directory to store the mock data.require('./endpoints');require('midway').start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, project: 'HelloMidway'});5. Add resources/run-mock-server-console.jsrequire('./endpoints');require('midway').start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, project: 'HelloMidway'});Please note that you will need to replace HelloMidway for key project field with your project name(without dashes).6. Add script to start mock server in package.json"scripts": { "lint": "eslint . --ext .js", "start-server": "node ./resources/run-mock-server-console.js"},7. Test mock server can be startednpm run start-server",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 101/Setting and Installing Mock Server"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-101-introduction": {
"title": "Introduction",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. What is Midway?We provide a mocking solution which can be leveraged to quickly stub the REST API responses that are used by your application during development or testing. The application points to the mock service host address instead of the live service, pre-recorded responses are then returned for various endpoints from the mock service. Since there is minimal logic when writing mock service, maintaining and development cost for mock service is minimal. Some of the major development pain-points addressed by the mocking solution are:Unstable servicesInconsistent DataTest against negative or unreal scenarios2. Architectural Explanation3. High Level Key FeaturesUI Interface: Mock service UI for manual testing/debugging.Test Reuse: Execute same test cases against mock or live service.Drop-And-Respond: Respond with a mocked data file based on the url route path automatically by dropping mocked data file in folder mapping to url path.Response Reuse: Ability to use same json response file and change data dynamically for mocked response for various variants.Test De-coupling: No coupling with test cases - Test cases are independent of mock implementation except that setting the desired response for the mock service (which has no impact if the test case is run against a live service).Common Utilities: Common utility methods are provided as part of this solution which allows quicker test development.HTTPS Support: HTTPS support for all the urls.Magellan/Nightwatch integration: Ability to use mocking service with Magellan tests.Parallel sessions: Support for single instance mock server for parallel processesSwagger integration: Automatic mock creator for web-services with swagger definition.Server states: Ability to mock server state.4. Mock TerminologyRoutesVariantsHandlerSetMockIdAdmin UIRespondWithFile",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 101/Introduction"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-101-introduction-to-variants": {
"title": "Introduction to Variants",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. What are variants?Variants allows to return a different data set for a given mocked route. Variants can be selected in the admin UI to determine what type of response a route should have. Routes are defined using the variant method on the Route object (returned by calling the route method). An object parameter is provided with the following attributesid: the variant id - used for the RESTful admin API and profile settingslabel: (optional) the variant label - used for display on the admin panelhandler: (optional) the HAPI route handler which provides the route responseVariants are useful because they allow you to test multiple scenarios that can happen with your route. Say, for example, you have a route exposing the ability to update a password. You might have several exceptional scenarios that you would want to test out (each could be a variant that you simply select to tell the route handler to use the appropriate response)the password was reset successfullythe password didn't pass validationthe old password wasn't entered correctlythe username doesn't existand so on...2. Default HandlerThe handler defined under route is the default handlermidway.route({ id: 'helloWorld', label: 'Hello World', path: '/helloWorld', method: 'GET', handler: function (req, reply) { reply('Hello World'); }});3. Creating a variantmidway.route({ id: 'message', label: 'Message', path: '/get/message', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { reply('Hello'); }}).variant({ id: 'hello', label: 'Hello World', handler: function (req, reply) { reply('Hello World'); }});4. Selecting a different variant to be returned from UIYou can select a different variant from admin UI to determine what type of response a route should have.5. Adding more variantsmidway.route({ id: 'message', label: 'Message', path: '/get/message', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { reply('Hello'); }}).variant({ id: 'hello', label: 'Hello World', handler: function (req, reply) { reply('Hello World'); }}).variant({ id: 'helloUniverse', label: 'Hello Universe', handler: function (req, reply) { reply('Hello Universe'); }});",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 101/Introduction to Variants"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-101-introduction-to-mocking-ui": {
"title": "Introduction to Mocking UI",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. Starting Mocking UITo start Mocking UI, after starting mock server navigate to http://localhost:8000/midway on your favorite browser.2. Navigating through Mocking UITry to navigate through Mocking UI to get better undertstanding of its functions.",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 101/Introduction to Mocking UI"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-101-exercise": {
"title": "Exercise",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. Create mock server with the followingAdd a GET route /get/message with default variant returning HelloAdd a variant that returns "Hello World"Add another variant that returns "Hello Universe"Add another GET route /get/numbers with default variant returning incremental values starting from 1Add a variant that returns even number starting from 2 in incrementsAdd another variant to return odd numbers starting from 1 in increments2. Start mock serverMake a REST call to /get/message and verify default variant returns 'Hello'Switch back and forth to other two variants and verify that you see 'Hello World' and 'Hello Universe' message respectively.Make a REST call to /get/numbers and verify default variant returns numbers in incremental orderSwitch back and forth to other two variants and verify that you see even and odd numbers in incremental order respectively.",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 101/Exercise"
},
"documentation-mocking-rweb-javascript-training-guide-mocking-101-adding-routes-for-mocking": {
"title": "Adding Routes for Mocking",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. What REST APIs can be mocked?GETHEADPOSTPUTPATCHDELETEOPTIONS2. Add a route to be mocked in endpoints.jsmidway.route({ id: 'helloWorld', label: 'Hello World', path: '/helloWorld', method: 'GET', handler: function (req, reply) { reply('Hello World'); }});Now start mock server and hit http://localhost:8000/helloWorld3. Understanding route parametersid: Unique route idlabel: Description of the routepath: Path of the routemethod: HTTP methodhandler: Function which handles the request for the path4. Adding multiple routes to be mockedmidway.route({ id: 'helloUniverse', label: 'Hello Universe', path: '/helloUniverse', method: 'GET', handler: function (req, reply) { reply('Hello Universe'); }});Now start mock server and hit http://localhost:8000/helloUniverse",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/Mocking 101/Adding Routes for Mocking"
},
"documentation-mocking-services-javascript-training-guide-mocking-401-state": {
"title": "State",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. What is state?State allows you to maintain state of your server, for example if a user is logged in or logged out. The mock server internally uses Hapi node server, which helps you return the state of the current application state. Within any response handler, use this.state('varName') to access an object stored in the state and this.state('varName', 'varValue') where varValue can be any type of object you want to set the state.2. How to set a state in mock server?midway.route({ path: '/api/login', label: 'LogIn', method: 'POST', handler: function(request, reply) { // now you can use this.state('loggedIn') in any route handler to see if the user has logged in this.state('loggedIn', true); reply().code(204); }});",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 401/State"
},
"documentation-mocking-services-javascript-training-guide-mocking-401-starting-https-server-with-mock-server": {
"title": "Starting HTTPS server with Mock Server",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. Updating run-mock-server-console.js to enable HTTPSrequire('./endpoints');var fs = require('fs');var midway = require('testarmada-midway'); midway.start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, httpsPort: 4444, project: 'HelloMidway'});The default port for HTTPS is 44442. Starting mock server with HTTPS enabledOnce you add the above code, the mock server will provide the HTTPS and HTTPS support by default. Hence when the mock server starts up, you will see both the ports open. Note that the mock server auto generates the certificates (key.pem and cert.pem). If you want to provide your own key and certificate, you can provide it under the mocked data directory.",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 401/Starting HTTPS server with Mock Server"
},
"documentation-mocking-services-javascript-training-guide-mocking-401-rest-apis": {
"title": "Rest APIs",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. Set VariantMethod : POSTSyntax : {host}:{port}/_admin/api/route/{routeId}Rest API : curl -H "Content-Type: application/json" -X POST -d '{"variant":"preorder"}' http://localhost:8000/_admin/api/route/getCollection?returnConfig=truemidway.route({ id: 'getCollection', label: 'Get Collection', path: '/product/grouping/api/collection/{collectionId}', variantLabel: 'default', handler: function(req, reply) { var response = getResponseData('/product/grouping/api/collection', 'default'); reply(response); }}).variant({ id: 'preorder', label: 'Get Pre-order Collection', handler: function (req, reply) { reply({message: 'hello pre-order'}); }});To get the config back as a response, add query parameter returnConfig=true as shown in example above2. Set Mock IdMethod : GETSyntax : {host}:{port}/_admin/api/midway/setMockId/{mockid}/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/setMockId/1234/default3. Get Mock IdMethod : GETSyntax : {host}:{port}/_admin/api/midway/getMockId/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/getMockId/default4. Reset Mock IdMethod : GETSyntax : {host}:{port}/_admin/api/midway/resetMockId/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/resetMockId/default5. Get Url CountMethod : GETSyntax : {host}:{port}/_admin/api/midway/getURLCount/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/getURLCount/default6. Reset Url CountMethod : GETSyntax : {host}:{port}/_admin/api/midway/resetURLCount/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/resetURLCount/default7. Re-set the state of Mock ServerMethod : POSTSyntax : {host}:{port}/_admin/api/state/resetRest API : curl -X POST http://localhost:8000/_admin/api/state/reset8. Register SessionMethod : GETSyntax : {host}:{port}/_admin/api/midway/registerSessionRest API : curl http://localhost:8000/_admin/api/midway/registerSession9. Get SessionsMethod : GETSyntax : {host}:{port}/_admin/api/midway/getSessionsRest API : curl http://localhost:8000/_admin/api/midway/getSessions10. Check SessionMethod : GETSyntax : {host}:{port}/_admin/api/midway/checkSession/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/checkSession/{sessionid}11. Close SessionMethod : GETSyntax : {host}:{port}/_admin/api/midway/closeSession/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/closeSession/{sessionid}",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 401/Rest APIs"
},
"documentation-mocking-services-javascript-training-guide-mocking-401-mocking-utility-methods": {
"title": "Mocking Utility Methods",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. RespondWithFile Utilitymidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }})Setting Codemidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400}); }})Custom File Locationmidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json'}); }})Setting Headersmidway.route({id: 'message',label: 'hello message',path: '/message',handler: function(req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json', headers: myHeaders});}});Setting Cookiesmidway.route({id: 'message',label: 'hello message',path: '/message',handler: function(req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; var cookies = [ {name: 'com.wm.customer', value: 'vz7.0b5c56'}, {name: 'CID', value: 'SmockedCID', options: {domain: 'domain', path: '/'}}, {name: 'anotherCookie', value: 'cookieValue'} ]; midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json', headers: myHeaders, cookies: cookies});}});Setting Delaymidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; var cookies = [ {name: 'com.wm.customer', value: 'vz7.0b5c56'}, {name: 'CID', value: 'SmockedCID', options: {domain: 'domain', path: '/'}}, {name: 'anotherCookie', value: 'cookieValue'} ]; midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json', headers: myHeaders, cookies: cookies, delay: 1000}); }});Modifying Static JSON responseIf you have many variants for a REST end point and the mocked data for all variants can use the same JSON response with few changes to the values, than this feature is what you need. This feature allows you to dynamically change a JSON file before sending the response back from the mock server for the request. It removes the need of having one to one mapping of static JSON files with each variants.// Static Response JSON File{ "id": "1234", "name": "toothpaste", "details": [ { "flavor": "Mint 1", "Size": "10", "Size_Type": "ounce" }, { "flavor": "Mint", "Size": "10", "Size_Type": "ounce" } ]}// Sample code for substituting id from 1234 to 7777 and flavor from Mint to Mint 2 for second array element in routesmidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { var dataToChange = { 'id': '7777', 'details[1].flavor': 'Mint 2' } midway.util.respondWithFile(this, reply, {transpose: dataToChange}); }});// Dynamic Response JSON File returned from Mock service{ "id": "7777", "name": "toothpaste", "details": [ { "flavor": "Mint 1", "Size": "10", "Size_Type": "ounce" }, { "flavor": "Mint 2", "Size": "10", "Size_Type": "ounce" } ]}2. Logging utilityMidway exposes a logging utility which can be used to log datamidway.log.debug('This is debug Message');midway.log.info('This is info Message');midway.log.error('This is error Message');midway.log.warn('This is warn Message');midway.log.setLogLevel('debug');midway.log.getLogLevel();midway.log.resetLogLevel();// default level is INFO3. Responding with a specific variant in handlers (respondWithMockVariant)This function will respond with a variant on the main route handler. The variant passed in MUST be the variant on existing route.midway.util.respondWithMockVariant(this, 'variant', reply);The variant passed in MUST be the variant on existing route.midway.route({ id: 'respondWithVariant', label: 'Respond With Variant', path: '/respondWithVariant', variantLabel: 'Respond With Variant Main Route', handler: function (req, reply) { midway.util.respondWithMockVariant(this, 'variant', reply); // make sure that the variant exist in the same route. }}).variant({ id: 'variant', label: 'Respond With Variant Variant Route', handler: function (req, reply) { reply({'message': 'I am an example of respond_with_mock_variant instead of response of main route '}); }});4. GetUrlCountTo get URL count for all Rest APIs mocked by mock serverMidway API : midway.getURLCount("default");5. ResetUrlCountTo resets URL count to zeroMidway API : midway.resetURLCount("default");",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 401/Mocking Utility Methods"
},
"documentation-mocking-services-javascript-training-guide-mocking-401-exercise": {
"title": "Exercise",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExerciseUpdate the previous mock server with the following:Add a logg-in route api/loginAdd a log-out route api/logoutAdd a state variable loggedIn and set true/false value based on the above APIs.Update the get/message default handler to return the message Hello: fname lname if user is logged in by reading from the query parameters otherwise Hello: Guest is the customer Id is less than equal to 5 characters.Update the get/message Hello Universe variant to modify the file to following using transpose data based on if user is logged in or logged out- User Logged In{ message: fname lname}- User Logged Out{ message: Guest}Start mock serverHit get/message with customer id length <=5 and see you should get Hello: GuestSet the variant to Hello UniverseHit get/message with customer id length <=5 and see you should get message: GuestHit api/loginSet the variant to defaultHit http://localhost:8000/get/message/12345?fname=John&lname=Doe with customer id length <=5 and see you should get Hello: John Doe.Set the variant to Hello UniverseHit http://localhost:8000/get/message/12345?fname=John&lname=Doe with customer id length <=5 and see you should get message:John DoeHit api/logout and repeat 5 to 7.Create and install certificates to enable HTTPS in Midway.Update run-mock-server-console.js to enable https in mock server.Start mock server and navigate to https://localhost:4444/_admin and repeat 5 to 12 steps.",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 401/Exercise"
},
"documentation-mocking-services-javascript-training-guide-mocking-301-setmockid": {
"title": "SetMockId",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. What is SetMockIdThis feature is very handy when you want to stub all the endpoints for a particular test without manually writing the paths for those endpoints. Generally applicable in scenarios where one page calls different endpoints according to test flows. You do not need to set variant or create variants for these endpoints. You will need to manually store the stubbed JSON files in the file structure location which are specified by your endpoints. The endpoints responses can be captured and stored under mocked data directory as a one time setup.2. How SetMockId works?ScenarioLets say your test case requires to mock two end points /api/message and /api/product/getStatus. These endpoints are called three times each. For the first end point you always want to return the same data (in json) while for the second endpoint you want to return the same data for the first and third call (in html) and a different data for the second call (in html).ImplementationCreate a folder under the mocked-data of your test directory (this folder name is configurable when you start your mock server by passing mockedDirectory option) by the name test1. Under this folder add the following files for your mocked response.api-message-GET.json - This will be returned for all the calls for the first endpoint with default response code 200api-product-getStatus-GET.html - This will be returned for all the calls for the second endpoint with default response code 200, except for the second and third call as it has its own fileapi-product-getStatus-GET-2.html - This will be returned for the second call for the second endpoint with default response code 200api-product-getStatus-GET-3-code-201.html - This will be returned for the third call for the second endpoint with response code 201Now set the setMockId either by mock api, UI or rest call to set to test1ExplanationThe underlying mock service automatically figures out the file extension so that you do not have to specify it. If you have the same file with multiple file extension than the following order is used:JSONHTMLTXTFirst file encountered of any other extensionOnce the midway.setMockId(“test1”) API is called, Midway only looks for the responses under the test1 folder. If it does not find the response, it will return 404 with the file name that it did not find. Midway internally keeps track of the number of times each individual endpoint is called after client.setMockId(“test1”) API is called and first looks for the file with count specific name such as api-message-GET-1.json, if it does not find the said file then it looks for the default file which is api-message-GET.json.3. Good To KnowIf setMockId is set, then custom file path in handlermidway.util.respondWithFile(this, reply, {filePath: ‘./message/GET/default.json’});and file based on URL path ./mocked-data/api/message/get/default.json are ignored for the mocked response. Here is the order followed for file lookup:SetMockIdCustom File Path for default or variants endpoints.File based on URL Path for default or variants endpoints.SetMockId does not work with in-line Handlermidway.route({ id: 'message', label: 'Message', path: '/get/message/{customerid}', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { var lname = req.query.lname; var fname = req.query.fname; var customerid = req.params.customerid; if (customerid.length > 5) { reply().code(400); } else { reply('Hello ' + fname + " " + lname); } }})",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 301/SetMockId"
},
"documentation-mocking-services-javascript-training-guide-mocking-301-parallel-sessions": {
"title": "Parallel Sessions",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. What is parallel sessions and why it's needed?Parallel sessions allows you to run multiple instance of server virtually while running only one server. This is helpful when you are running multiple test cases which access the same routes but different variants as parallel sessions allow you to set different variants on same routes without conflicting. This saves CPU and RAM both as only one server is running instead of multiple.2. How Parallel Sessions works internally?3. How to add parallel sessions?To add parallel sessions, modify run-mock-server-console.js to add 'sessions' parameter.require('./endpoints');var midway = require('testarmada-midway');midway.start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, sessions: 2, project: 'HelloMidway'});You can also start or add sessions via command line argumentnode resources/run-mock-server-console.js --midwaySessions 2If you pass sessions = 2, there will be two parallel sessions along with one default session.4. Supported APIs for Parallel sessionsRegister SessionTo register sessions to be usedvar sessionId = midway.registerSession();Get SessionsTo get all the active sessionsvar activeSessions = midway.getSessions();Check SessionTo check the session status (Available or In-Use or invalid)var sessionStatus = midway.checkSession(sessionId);Close SessionTo de-register session for later usevar closeSession = midway.closeSession(sessionId);5. Using Parallel SessionsTo use a parallel session call the following api:curl http://localhost:8000/_admin/api/midway/registerSessionormidway.registerSession()and a session id will be returned.Append this sessionId to the mocked host address to use this parallel session. For ex: If your mock host server is http://localhost:8080 and your session id is 112233 then the mock server address for this parallel session will be http://localhost:8080/112233.6. Verifying parallel sessionsStart mock server with two sessions. Now go to the 'Message' route. You will see three routes for message, default and two for parallel sessions that you just added. Now for each route choose a different variant and hit the URL icon. You will see that each time you will get a different value though you are hitting the same route.7. Understanding the Midway UI with sessionsTry to go through Midway UI to understand sessions.",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 301/Parallel Sessions"
},
"documentation-mocking-services-javascript-training-guide-mocking-301-exercise": {
"title": "Exercise",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExerciseUpdate the previous mock server with the following:Update the Hello World variant of 'get/message' request toRemove the header parametersReturn the file as before by using RespondWithFile without handlerUpdate the default handler to return ONLY code 400 if the customer id is greater than 5 charactersStart mock server and test Step 1Now add data for setMockId for /get/message and /get/number routes.Return the following for URL hit count 1/get/message{ "message" : 1}/get/number{ "number" : 1}Return the following for URL hit count 2/get/message{ "message" : 2}/get/number{ "number" : 2}Return the following for default/get/message{ "message" : "Undefined"}/get/number{ "number" : "Undefined"}Call API to setMockId to the folder name via Midway UIHit the rest endpoint /get/message and /get/number one time each and verify the response is "message" : 1 and "number" : 1 respectively.Hit the rest endpoint /get/message and /get/number once more and verify the response for second hit is "message" : 2 and "number" : 2 respectively.Hit the rest endpoint /get/message and /get/number one more time to verify that the response is "message" : "undefined" and "number" : "undefined" respectively.Call ResetMockId API via Midway UIHit the rest endpoint /get/message and /get/number once each and verify the response is based on the handler and not on SetMockId - You may have to add appropriate file based on the route path.Update run-mock-server-console.js to add two parallel sessions to the server.Now call GetSessionId to register a session using Midway UI.Now set Hello World and Hello Universe variant for get/message api for the two sessions Ids respectively.Now hit the server https://localhost:8000/sessionId/get/message for different session Ids and verify that you get different responses as per each variant.",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 301/Exercise"
},
"documentation-mocking-services-javascript-training-guide-mocking-301-different-ways-of-returning-response-data": {
"title": "Different ways of returning response data",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. Returning only the codemidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { reply().code(400); }})2. Using RespondWithFile without handlermidway.route({ path: '/api/customer/getId', label: 'Get Customer Id', method: 'GET', }).respondWithFile();3. Returning static mocked data with a response codemidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400}); }})",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 301/Different ways of returning response data"
},
"documentation-mocking-services-javascript-training-guide-mocking-301-apis-for-setmockid": {
"title": "APIs for SetMockId",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. SetMockIdmidway.setMockId("1234", "default");2. GetMockIdmidway.getMockId("default");3. ResetMockIdmidway.resetMockId("default");",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 301/APIs for SetMockId"
},
"documentation-mocking-services-javascript-training-guide-mocking-201-returning-response-from-a-file": {
"title": "Returning Response from a File",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. What does it mean?This feature allows you to respond with a data stored in a file instead of hard coding the response data in the routes definition. This way user does not have to change the response rather can just swap the file with different data.2. How it works?midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }});In the above setup, file needed for default route, which is /get/fromFile should be located at ./mocked-data/get/fromFile/GET/default.json3. What is mockedDirectory Path?Mocked directory path is the location to the base directory where all your mocked response file will be stored. This parameter is defined in run-mock-server-console.js file. It is defined at the start of mock server as shown in the code below:require('./endpoints-Midway-201');require('midway').start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, project: 'HelloMidway'});4. Automatic calculation of file locationThe path to the mocked data file is auto-calculated based on the route path. For variants, the name of the file should be changed from default to the variant name as shown below:midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }}).variant({ id: 'textData', label: 'Text Data', handler: function (req, reply) { midway.util.respondWithFile(this, reply); }})In the above example, mock server would look for ./resources/mocked-data/get/fromFile/GET/textData.txt file for the variant textData5. Providing custom path to the response fileA custom file path could also be provided for a mocked data file. to do so, use the following code:midway.route({ id: 'CustomResponseFile', label: 'Response From Custom Path', path: '/get/customFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {filePath: './custom.json'}); }})Midway will look for the file under MockedDirectory only but at ./resources/mocked-data/custom.json",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 201/Returning Response from a File"
},
"documentation-mocking-services-javascript-training-guide-mocking-201-request-call-information": {
"title": "Request Call Information",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. Query ParametersLet's say you go to the following URL: http://localhost:8000/get/customerInfo/12345?ctype=new . To read the query parameter, do the following:var ctype = req.query.ctype;To run the above scenario, hit the following in any browser with Midway server running: http://localhost:8000/get/customerInfo/12345?ctype=new after updating the route tomidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { var id = req.params.customerid; var ctype = req.query.ctype; var replyString = 'Customer Type: ' + ctype + ' customer id: ' + id; reply(replyString); }});2. Header informationLet's say there is a header parameter 'name' with value 'John' is passed with the request. To read the testHeader parameter, do the following:var req = req.raw.req;var name = req.headers.name;To run the above scenario, use postman to make the following get call: http://localhost:8000/get/customerInfo/12345?ctype=new and add header 'name' with value 'John' after updating the route tomidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { var id = req.params.customerid; var ctype = req.query.ctype; var req = req.raw.req; var name = req.headers.name; var replyString = 'Customer Type: ' + ctype + ' customer id: ' + id + ' nameFromHeader: ' + name; reply(replyString); }});3. PayloadThe payload can be read using the following code://fname would be "Bob" if the posted body content (as JSON) was {"fname": "Bob"}var fname = req.payload.fname;To run the above scenario, use postman to make the following POST call: http://localhost:8000/payload and add payload {"fname": "Bob"} in the request.midway.route({ id: 'payload', label: 'Reading Payload', path: '/payload', method: 'POST', variantLabel: 'Payload', handler: function (req, reply) { var fname = req.payload.fname; reply(fname); }});4. Content TypesThe mock module is independent of content-types i.e. user can set any content type and mocking route is intercepted only based on the path defined in the mocked routes file.",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 201/Request Call Information"
},
"documentation-mocking-services-javascript-training-guide-mocking-201-exercise": {
"title": "Exercise",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. Update the previous mock server with the followinga. Update the route /get/message to a dynamic URL which takes customer id as a parameter.b. Update the 'Hello World' variant to- return the following file with auto file location calculation.json { "message" : "Hello World" }- Set the following header params in response{ fname: John lname: Doe }Update the Hello Universe variantto return the following file and the file location should be hard coded.{ "message" : "Hello Universe"}Set the following cookie params in response{ customerId: 123456}Update the default handler to do the following:Add reading of query parameter 'fname' and 'lname' from the request.If the customer id is greater than 5 charactersreturn 'invalid id' as responseIf the customer id is less than or equal to 5 charactersreturn following response from the handler (NOT Using The File)Hello - fname lnameAdd a POST route /set/customerId and in default handler read the payload value and log it on console.{ "customerid": 123456}2. Start mock serverMake a REST call to /get/message with customer id greater than 5 characters and check the response is Invalid IdMake a REST call to /get/message with customer id equal to 5 characters and check the response to be Hello undefined undefinedMake a REST call to http://localhost:8000/get/message/12345?fname=John&lname=Doe and check the response to be Hello John DoeSwitch to Hello World variant and check the response is "message" : "Hello World" and use dev tools on Chrome browser to verify that the header params are set (fname: John and lname: Doe)Switch to Hello Universe variant and check the response is "message" : "Hello Universe" and use dev tools on Chrome browser to verify that the cookie is set (customerId: 123456)Make a post call to mock server at http://localhost:8000/set/customerId using Postman (or any other HTTP client) with the following data and verify that 12345 is logged on the console{ "customerId" : 12345}",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 201/Exercise"
},
"documentation-mocking-services-javascript-training-guide-mocking-201-dynamic-urls": {
"title": "Dynamic URLs",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. How to create dynamic urls/get/customerInfo/{customerid}/{zipcode}2. Adding a dynamic URL in mock servermidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { reply('How to read the customer id :('); }});3. Reading dynamic URL parametersvar id = req.params.customerid;4. Using dynamic values to define responsemidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { var id = req.params.customerid; reply('Customer id is ' + id + ' :)'); }});5. Passing dynamic URL parameters from the Midway UITry to pass dynamic url parameters generated from Midway UI",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 201/Dynamic URLs"
},
"documentation-mocking-services-javascript-training-guide-mocking-201-customizing-mocked-response": {
"title": "Customizing Mocked Response",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. Set custom headersmidway.route({ id: 'header', label: 'Custom Headers', path: '/set/headers', handler: function(req, reply) { reply({message: 'custom headers'}) .header('header1', 'test1') .header('header2', 'test2') .header('header3', 'test3') }}) midway.route({ id: 'header', label: 'Custom Headers', path: '/set/headers', handler: function (req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; midway.util.respondWithFile(this, reply, {headers: myHeaders}); }});2. Set custom cookiesmidway.route({ id: 'cookies', label: 'Custom Cookies', path: '/set/cookies', handler: function(req, reply) { reply({message: 'test'}) .state('cookie1', 'testCookie1') .state('cookie2', 'testCookie2') }}); midway.route({ id: 'cookies', label: 'Custom Cookies', path: '/set/cookies', handler: function (req, reply) { var cookies = [ {name: 'cookie1', value: 'testCookie1'}, {name: 'cookie2', value: 'testCookie2'}, ]; midway.util.respondWithFile(this, reply, {cookies: cookies}); }});3. Set CORS headersvar corsHeaders = { origin: ['*'], headers: ["Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"], credentials: true,} // Itemsmidway.route({ id: 'corsheaders', label: 'CORS', path: '/set/cors', config: { cors: corsHeaders }, handler: function(req, reply) { reply('cors headers set'); }});",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 201/Customizing Mocked Response"
},
"documentation-mocking-services-javascript-training-guide-mocking-101-setting-and-installing-mock-server": {
"title": "Setting and Installing Mock Server",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. Pre-requisitesnode.js 4+ (npm is included in the package)2. Add mock dependency to package.json"dependencies": { "testarmada-midway": "^1.0.1"}3. Install mock dependency with npm installRun npm install command to install mock related dependencies.4. Add resources/endpoints.js and create ./resources/mocked-data directory to store the mock data.require('./endpoints');require('midway').start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, project: 'HelloMidway'});5. Add resources/run-mock-server-console.jsrequire('./endpoints');require('midway').start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, project: 'HelloMidway'});Please note that you will need to replace HelloMidway for key project field with your project name(without dashes).6. Add script to start mock server in package.json"scripts": { "lint": "eslint . --ext .js", "start-server": "node ./resources/run-mock-server-console.js"},7. Test mock server can be startednpm run start-server",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 101/Setting and Installing Mock Server"
},
"documentation-mocking-services-javascript-training-guide-mocking-101-introduction": {
"title": "Introduction",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. What is Midway?We provide a mocking solution which can be leveraged to quickly stub the REST API responses that are used by your application during development or testing. The application points to the mock service host address instead of the live service, pre-recorded responses are then returned for various endpoints from the mock service. Since there is minimal logic when writing mock service, maintaining and development cost for mock service is minimal. Some of the major development pain-points addressed by the mocking solution are:Unstable servicesInconsistent DataTest against negative or unreal scenarios2. Architectural Explanation3. High Level Key FeaturesUI Interface: Mock service UI for manual testing/debugging.Test Reuse: Execute same test cases against mock or live service.Drop-And-Respond: Respond with a mocked data file based on the url route path automatically by dropping mocked data file in folder mapping to url path.Response Reuse: Ability to use same json response file and change data dynamically for mocked response for various variants.Test De-coupling: No coupling with test cases - Test cases are independent of mock implementation except that setting the desired response for the mock service (which has no impact if the test case is run against a live service).Common Utilities: Common utility methods are provided as part of this solution which allows quicker test development.HTTPS Support: HTTPS support for all the urls.Magellan/Nightwatch integration: Ability to use mocking service with Magellan tests.Parallel sessions: Support for single instance mock server for parallel processesSwagger integration: Automatic mock creator for web-services with swagger definition.Server states: Ability to mock server state.4. Mock TerminologyRoutesVariantsHandlerSetMockIdAdmin UIRespondWithFile",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 101/Introduction"
},
"documentation-mocking-services-javascript-training-guide-mocking-101-introduction-to-variants": {
"title": "Introduction to Variants",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. What are variants?Variants allows to return a different data set for a given mocked route. Variants can be selected in the admin UI to determine what type of response a route should have. Routes are defined using the variant method on the Route object (returned by calling the route method). An object parameter is provided with the following attributesid: the variant id - used for the RESTful admin API and profile settingslabel: (optional) the variant label - used for display on the admin panelhandler: (optional) the HAPI route handler which provides the route responseVariants are useful because they allow you to test multiple scenarios that can happen with your route. Say, for example, you have a route exposing the ability to update a password. You might have several exceptional scenarios that you would want to test out (each could be a variant that you simply select to tell the route handler to use the appropriate response)the password was reset successfullythe password didn't pass validationthe old password wasn't entered correctlythe username doesn't existand so on...2. Default HandlerThe handler defined under route is the default handlermidway.route({ id: 'helloWorld', label: 'Hello World', path: '/helloWorld', method: 'GET', handler: function (req, reply) { reply('Hello World'); }});3. Creating a variantmidway.route({ id: 'message', label: 'Message', path: '/get/message', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { reply('Hello'); }}).variant({ id: 'hello', label: 'Hello World', handler: function (req, reply) { reply('Hello World'); }});4. Selecting a different variant to be returned from UIYou can select a different variant from admin UI to determine what type of response a route should have.5. Adding more variantsmidway.route({ id: 'message', label: 'Message', path: '/get/message', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { reply('Hello'); }}).variant({ id: 'hello', label: 'Hello World', handler: function (req, reply) { reply('Hello World'); }}).variant({ id: 'helloUniverse', label: 'Hello Universe', handler: function (req, reply) { reply('Hello Universe'); }});",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 101/Introduction to Variants"
},
"documentation-mocking-services-javascript-training-guide-mocking-101-introduction-to-mocking-ui": {
"title": "Introduction to Mocking UI",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. Starting Mocking UITo start Mocking UI, after starting mock server navigate to http://localhost:8000/midway on your favorite browser.2. Navigating through Mocking UITry to navigate through Mocking UI to get better undertstanding of its functions.",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 101/Introduction to Mocking UI"
},
"documentation-mocking-services-javascript-training-guide-mocking-101-exercise": {
"title": "Exercise",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. Create mock server with the followingAdd a GET route /get/message with default variant returning HelloAdd a variant that returns "Hello World"Add another variant that returns "Hello Universe"Add another GET route /get/numbers with default variant returning incremental values starting from 1Add a variant that returns even number starting from 2 in incrementsAdd another variant to return odd numbers starting from 1 in increments2. Start mock serverMake a REST call to /get/message and verify default variant returns 'Hello'Switch back and forth to other two variants and verify that you see 'Hello World' and 'Hello Universe' message respectively.Make a REST call to /get/numbers and verify default variant returns numbers in incremental orderSwitch back and forth to other two variants and verify that you see even and odd numbers in incremental order respectively.",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 101/Exercise"
},
"documentation-mocking-services-javascript-training-guide-mocking-101-adding-routes-for-mocking": {
"title": "Adding Routes for Mocking",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. What REST APIs can be mocked?GETHEADPOSTPUTPATCHDELETEOPTIONS2. Add a route to be mocked in endpoints.jsmidway.route({ id: 'helloWorld', label: 'Hello World', path: '/helloWorld', method: 'GET', handler: function (req, reply) { reply('Hello World'); }});Now start mock server and hit http://localhost:8000/helloWorld3. Understanding route parametersid: Unique route idlabel: Description of the routepath: Path of the routemethod: HTTP methodhandler: Function which handles the request for the path4. Adding multiple routes to be mockedmidway.route({ id: 'helloUniverse', label: 'Hello Universe', path: '/helloUniverse', method: 'GET', handler: function (req, reply) { reply('Hello Universe'); }});Now start mock server and hit http://localhost:8000/helloUniverse",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/Mocking 101/Adding Routes for Mocking"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-401-state": {
"title": "State",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. What is state?State allows you to maintain state of your server, for example if a user is logged in or logged out. The mock server internally uses Hapi node server, which helps you return the state of the current application state. Within any response handler, use this.state('varName') to access an object stored in the state and this.state('varName', 'varValue') where varValue can be any type of object you want to set the state.2. How to set a state in mock server?midway.route({ path: '/api/login', label: 'LogIn', method: 'POST', handler: function(request, reply) { // now you can use this.state('loggedIn') in any route handler to see if the user has logged in this.state('loggedIn', true); reply().code(204); }});",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 401/State"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-401-starting-https-server-with-mock-server": {
"title": "Starting HTTPS server with Mock Server",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. Updating run-mock-server-console.js to enable HTTPSrequire('./endpoints');var fs = require('fs');var midway = require('testarmada-midway'); midway.start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, httpsPort: 4444, project: 'HelloMidway'});The default port for HTTPS is 44442. Starting mock server with HTTPS enabledOnce you add the above code, the mock server will provide the HTTPS and HTTPS support by default. Hence when the mock server starts up, you will see both the ports open. Note that the mock server auto generates the certificates (key.pem and cert.pem). If you want to provide your own key and certificate, you can provide it under the mocked data directory.",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 401/Starting HTTPS server with Mock Server"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-401-rest-apis": {
"title": "Rest APIs",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. Set VariantMethod : POSTSyntax : {host}:{port}/_admin/api/route/{routeId}Rest API : curl -H "Content-Type: application/json" -X POST -d '{"variant":"preorder"}' http://localhost:8000/_admin/api/route/getCollection?returnConfig=truemidway.route({ id: 'getCollection', label: 'Get Collection', path: '/product/grouping/api/collection/{collectionId}', variantLabel: 'default', handler: function(req, reply) { var response = getResponseData('/product/grouping/api/collection', 'default'); reply(response); }}).variant({ id: 'preorder', label: 'Get Pre-order Collection', handler: function (req, reply) { reply({message: 'hello pre-order'}); }});To get the config back as a response, add query parameter returnConfig=true as shown in example above2. Set Mock IdMethod : GETSyntax : {host}:{port}/_admin/api/midway/setMockId/{mockid}/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/setMockId/1234/default3. Get Mock IdMethod : GETSyntax : {host}:{port}/_admin/api/midway/getMockId/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/getMockId/default4. Reset Mock IdMethod : GETSyntax : {host}:{port}/_admin/api/midway/resetMockId/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/resetMockId/default5. Get Url CountMethod : GETSyntax : {host}:{port}/_admin/api/midway/getURLCount/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/getURLCount/default6. Reset Url CountMethod : GETSyntax : {host}:{port}/_admin/api/midway/resetURLCount/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/resetURLCount/default7. Re-set the state of Mock ServerMethod : POSTSyntax : {host}:{port}/_admin/api/state/resetRest API : curl -X POST http://localhost:8000/_admin/api/state/reset8. Register SessionMethod : GETSyntax : {host}:{port}/_admin/api/midway/registerSessionRest API : curl http://localhost:8000/_admin/api/midway/registerSession9. Get SessionsMethod : GETSyntax : {host}:{port}/_admin/api/midway/getSessionsRest API : curl http://localhost:8000/_admin/api/midway/getSessions10. Check SessionMethod : GETSyntax : {host}:{port}/_admin/api/midway/checkSession/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/checkSession/{sessionid}11. Close SessionMethod : GETSyntax : {host}:{port}/_admin/api/midway/closeSession/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/closeSession/{sessionid}",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 401/Rest APIs"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-401-mocking-utility-methods": {
"title": "Mocking Utility Methods",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. RespondWithFile Utilitymidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }})Setting Codemidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400}); }})Custom File Locationmidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json'}); }})Setting Headersmidway.route({id: 'message',label: 'hello message',path: '/message',handler: function(req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json', headers: myHeaders});}});Setting Cookiesmidway.route({id: 'message',label: 'hello message',path: '/message',handler: function(req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; var cookies = [ {name: 'com.wm.customer', value: 'vz7.0b5c56'}, {name: 'CID', value: 'SmockedCID', options: {domain: 'domain', path: '/'}}, {name: 'anotherCookie', value: 'cookieValue'} ]; midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json', headers: myHeaders, cookies: cookies});}});Setting Delaymidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; var cookies = [ {name: 'com.wm.customer', value: 'vz7.0b5c56'}, {name: 'CID', value: 'SmockedCID', options: {domain: 'domain', path: '/'}}, {name: 'anotherCookie', value: 'cookieValue'} ]; midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json', headers: myHeaders, cookies: cookies, delay: 1000}); }});Modifying Static JSON responseIf you have many variants for a REST end point and the mocked data for all variants can use the same JSON response with few changes to the values, than this feature is what you need. This feature allows you to dynamically change a JSON file before sending the response back from the mock server for the request. It removes the need of having one to one mapping of static JSON files with each variants.// Static Response JSON File{ "id": "1234", "name": "toothpaste", "details": [ { "flavor": "Mint 1", "Size": "10", "Size_Type": "ounce" }, { "flavor": "Mint", "Size": "10", "Size_Type": "ounce" } ]}// Sample code for substituting id from 1234 to 7777 and flavor from Mint to Mint 2 for second array element in routesmidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { var dataToChange = { 'id': '7777', 'details[1].flavor': 'Mint 2' } midway.util.respondWithFile(this, reply, {transpose: dataToChange}); }});// Dynamic Response JSON File returned from Mock service{ "id": "7777", "name": "toothpaste", "details": [ { "flavor": "Mint 1", "Size": "10", "Size_Type": "ounce" }, { "flavor": "Mint 2", "Size": "10", "Size_Type": "ounce" } ]}2. Logging utilityMidway exposes a logging utility which can be used to log datamidway.log.debug('This is debug Message');midway.log.info('This is info Message');midway.log.error('This is error Message');midway.log.warn('This is warn Message');midway.log.setLogLevel('debug');midway.log.getLogLevel();midway.log.resetLogLevel();// default level is INFO3. Responding with a specific variant in handlers (respondWithMockVariant)This function will respond with a variant on the main route handler. The variant passed in MUST be the variant on existing route.midway.util.respondWithMockVariant(this, 'variant', reply);The variant passed in MUST be the variant on existing route.midway.route({ id: 'respondWithVariant', label: 'Respond With Variant', path: '/respondWithVariant', variantLabel: 'Respond With Variant Main Route', handler: function (req, reply) { midway.util.respondWithMockVariant(this, 'variant', reply); // make sure that the variant exist in the same route. }}).variant({ id: 'variant', label: 'Respond With Variant Variant Route', handler: function (req, reply) { reply({'message': 'I am an example of respond_with_mock_variant instead of response of main route '}); }});4. GetUrlCountTo get URL count for all Rest APIs mocked by mock serverMidway API : midway.getURLCount("default");5. ResetUrlCountTo resets URL count to zeroMidway API : midway.resetURLCount("default");",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 401/Mocking Utility Methods"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-401-exercise": {
"title": "Exercise",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExerciseUpdate the previous mock server with the following:Add a logg-in route api/loginAdd a log-out route api/logoutAdd a state variable loggedIn and set true/false value based on the above APIs.Update the get/message default handler to return the message Hello: fname lname if user is logged in by reading from the query parameters otherwise Hello: Guest is the customer Id is less than equal to 5 characters.Update the get/message Hello Universe variant to modify the file to following using transpose data based on if user is logged in or logged out- User Logged In{ message: fname lname}- User Logged Out{ message: Guest}Start mock serverHit get/message with customer id length <=5 and see you should get Hello: GuestSet the variant to Hello UniverseHit get/message with customer id length <=5 and see you should get message: GuestHit api/loginSet the variant to defaultHit http://localhost:8000/get/message/12345?fname=John&lname=Doe with customer id length <=5 and see you should get Hello: John Doe.Set the variant to Hello UniverseHit http://localhost:8000/get/message/12345?fname=John&lname=Doe with customer id length <=5 and see you should get message:John DoeHit api/logout and repeat 5 to 7.Create and install certificates to enable HTTPS in Midway.Update run-mock-server-console.js to enable https in mock server.Start mock server and navigate to https://localhost:4444/_admin and repeat 5 to 12 steps.",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 401/Exercise"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-301-setmockid": {
"title": "SetMockId",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. What is SetMockIdThis feature is very handy when you want to stub all the endpoints for a particular test without manually writing the paths for those endpoints. Generally applicable in scenarios where one page calls different endpoints according to test flows. You do not need to set variant or create variants for these endpoints. You will need to manually store the stubbed JSON files in the file structure location which are specified by your endpoints. The endpoints responses can be captured and stored under mocked data directory as a one time setup.2. How SetMockId works?ScenarioLets say your test case requires to mock two end points /api/message and /api/product/getStatus. These endpoints are called three times each. For the first end point you always want to return the same data (in json) while for the second endpoint you want to return the same data for the first and third call (in html) and a different data for the second call (in html).ImplementationCreate a folder under the mocked-data of your test directory (this folder name is configurable when you start your mock server by passing mockedDirectory option) by the name test1. Under this folder add the following files for your mocked response.api-message-GET.json - This will be returned for all the calls for the first endpoint with default response code 200api-product-getStatus-GET.html - This will be returned for all the calls for the second endpoint with default response code 200, except for the second and third call as it has its own fileapi-product-getStatus-GET-2.html - This will be returned for the second call for the second endpoint with default response code 200api-product-getStatus-GET-3-code-201.html - This will be returned for the third call for the second endpoint with response code 201Now set the setMockId either by mock api, UI or rest call to set to test1ExplanationThe underlying mock service automatically figures out the file extension so that you do not have to specify it. If you have the same file with multiple file extension than the following order is used:JSONHTMLTXTFirst file encountered of any other extensionOnce the midway.setMockId(“test1”) API is called, Midway only looks for the responses under the test1 folder. If it does not find the response, it will return 404 with the file name that it did not find. Midway internally keeps track of the number of times each individual endpoint is called after client.setMockId(“test1”) API is called and first looks for the file with count specific name such as api-message-GET-1.json, if it does not find the said file then it looks for the default file which is api-message-GET.json.3. Good To KnowIf setMockId is set, then custom file path in handlermidway.util.respondWithFile(this, reply, {filePath: ‘./message/GET/default.json’});and file based on URL path ./mocked-data/api/message/get/default.json are ignored for the mocked response. Here is the order followed for file lookup:SetMockIdCustom File Path for default or variants endpoints.File based on URL Path for default or variants endpoints.SetMockId does not work with in-line Handlermidway.route({ id: 'message', label: 'Message', path: '/get/message/{customerid}', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { var lname = req.query.lname; var fname = req.query.fname; var customerid = req.params.customerid; if (customerid.length > 5) { reply().code(400); } else { reply('Hello ' + fname + " " + lname); } }})",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 301/SetMockId"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-301-parallel-sessions": {
"title": "Parallel Sessions",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. What is parallel sessions and why it's needed?Parallel sessions allows you to run multiple instance of server virtually while running only one server. This is helpful when you are running multiple test cases which access the same routes but different variants as parallel sessions allow you to set different variants on same routes without conflicting. This saves CPU and RAM both as only one server is running instead of multiple.2. How Parallel Sessions works internally?3. How to add parallel sessions?To add parallel sessions, modify run-mock-server-console.js to add 'sessions' parameter.require('./endpoints');var midway = require('testarmada-midway');midway.start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, sessions: 2, project: 'HelloMidway'});You can also start or add sessions via command line argumentnode resources/run-mock-server-console.js --midwaySessions 2If you pass sessions = 2, there will be two parallel sessions along with one default session.4. Supported APIs for Parallel sessionsRegister SessionTo register sessions to be usedvar sessionId = midway.registerSession();Get SessionsTo get all the active sessionsvar activeSessions = midway.getSessions();Check SessionTo check the session status (Available or In-Use or invalid)var sessionStatus = midway.checkSession(sessionId);Close SessionTo de-register session for later usevar closeSession = midway.closeSession(sessionId);5. Using Parallel SessionsTo use a parallel session call the following api:curl http://localhost:8000/_admin/api/midway/registerSessionormidway.registerSession()and a session id will be returned.Append this sessionId to the mocked host address to use this parallel session. For ex: If your mock host server is http://localhost:8080 and your session id is 112233 then the mock server address for this parallel session will be http://localhost:8080/112233.6. Verifying parallel sessionsStart mock server with two sessions. Now go to the 'Message' route. You will see three routes for message, default and two for parallel sessions that you just added. Now for each route choose a different variant and hit the URL icon. You will see that each time you will get a different value though you are hitting the same route.7. Understanding the Midway UI with sessionsTry to go through Midway UI to understand sessions.",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 301/Parallel Sessions"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-301-exercise": {
"title": "Exercise",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExerciseUpdate the previous mock server with the following:Update the Hello World variant of 'get/message' request toRemove the header parametersReturn the file as before by using RespondWithFile without handlerUpdate the default handler to return ONLY code 400 if the customer id is greater than 5 charactersStart mock server and test Step 1Now add data for setMockId for /get/message and /get/number routes.Return the following for URL hit count 1/get/message{ "message" : 1}/get/number{ "number" : 1}Return the following for URL hit count 2/get/message{ "message" : 2}/get/number{ "number" : 2}Return the following for default/get/message{ "message" : "Undefined"}/get/number{ "number" : "Undefined"}Call API to setMockId to the folder name via Midway UIHit the rest endpoint /get/message and /get/number one time each and verify the response is "message" : 1 and "number" : 1 respectively.Hit the rest endpoint /get/message and /get/number once more and verify the response for second hit is "message" : 2 and "number" : 2 respectively.Hit the rest endpoint /get/message and /get/number one more time to verify that the response is "message" : "undefined" and "number" : "undefined" respectively.Call ResetMockId API via Midway UIHit the rest endpoint /get/message and /get/number once each and verify the response is based on the handler and not on SetMockId - You may have to add appropriate file based on the route path.Update run-mock-server-console.js to add two parallel sessions to the server.Now call GetSessionId to register a session using Midway UI.Now set Hello World and Hello Universe variant for get/message api for the two sessions Ids respectively.Now hit the server https://localhost:8000/sessionId/get/message for different session Ids and verify that you get different responses as per each variant.",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 301/Exercise"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-301-different-ways-of-returning-response-data": {
"title": "Different ways of returning response data",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. Returning only the codemidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { reply().code(400); }})2. Using RespondWithFile without handlermidway.route({ path: '/api/customer/getId', label: 'Get Customer Id', method: 'GET', }).respondWithFile();3. Returning static mocked data with a response codemidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400}); }})",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 301/Different ways of returning response data"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-301-apis-for-setmockid": {
"title": "APIs for SetMockId",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. SetMockIdmidway.setMockId("1234", "default");2. GetMockIdmidway.getMockId("default");3. ResetMockIdmidway.resetMockId("default");",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 301/APIs for SetMockId"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-201-returning-response-from-a-file": {
"title": "Returning Response from a File",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. What does it mean?This feature allows you to respond with a data stored in a file instead of hard coding the response data in the routes definition. This way user does not have to change the response rather can just swap the file with different data.2. How it works?midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }});In the above setup, file needed for default route, which is /get/fromFile should be located at ./mocked-data/get/fromFile/GET/default.json3. What is mockedDirectory Path?Mocked directory path is the location to the base directory where all your mocked response file will be stored. This parameter is defined in run-mock-server-console.js file. It is defined at the start of mock server as shown in the code below:require('./endpoints-Midway-201');require('midway').start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, project: 'HelloMidway'});4. Automatic calculation of file locationThe path to the mocked data file is auto-calculated based on the route path. For variants, the name of the file should be changed from default to the variant name as shown below:midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }}).variant({ id: 'textData', label: 'Text Data', handler: function (req, reply) { midway.util.respondWithFile(this, reply); }})In the above example, mock server would look for ./resources/mocked-data/get/fromFile/GET/textData.txt file for the variant textData5. Providing custom path to the response fileA custom file path could also be provided for a mocked data file. to do so, use the following code:midway.route({ id: 'CustomResponseFile', label: 'Response From Custom Path', path: '/get/customFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {filePath: './custom.json'}); }})Midway will look for the file under MockedDirectory only but at ./resources/mocked-data/custom.json",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 201/Returning Response from a File"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-201-request-call-information": {
"title": "Request Call Information",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. Query ParametersLet's say you go to the following URL: http://localhost:8000/get/customerInfo/12345?ctype=new . To read the query parameter, do the following:var ctype = req.query.ctype;To run the above scenario, hit the following in any browser with Midway server running: http://localhost:8000/get/customerInfo/12345?ctype=new after updating the route tomidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { var id = req.params.customerid; var ctype = req.query.ctype; var replyString = 'Customer Type: ' + ctype + ' customer id: ' + id; reply(replyString); }});2. Header informationLet's say there is a header parameter 'name' with value 'John' is passed with the request. To read the testHeader parameter, do the following:var req = req.raw.req;var name = req.headers.name;To run the above scenario, use postman to make the following get call: http://localhost:8000/get/customerInfo/12345?ctype=new and add header 'name' with value 'John' after updating the route tomidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { var id = req.params.customerid; var ctype = req.query.ctype; var req = req.raw.req; var name = req.headers.name; var replyString = 'Customer Type: ' + ctype + ' customer id: ' + id + ' nameFromHeader: ' + name; reply(replyString); }});3. PayloadThe payload can be read using the following code://fname would be "Bob" if the posted body content (as JSON) was {"fname": "Bob"}var fname = req.payload.fname;To run the above scenario, use postman to make the following POST call: http://localhost:8000/payload and add payload {"fname": "Bob"} in the request.midway.route({ id: 'payload', label: 'Reading Payload', path: '/payload', method: 'POST', variantLabel: 'Payload', handler: function (req, reply) { var fname = req.payload.fname; reply(fname); }});4. Content TypesThe mock module is independent of content-types i.e. user can set any content type and mocking route is intercepted only based on the path defined in the mocked routes file.",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 201/Request Call Information"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-201-exercise": {
"title": "Exercise",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. Update the previous mock server with the followinga. Update the route /get/message to a dynamic URL which takes customer id as a parameter.b. Update the 'Hello World' variant to- return the following file with auto file location calculation.json { "message" : "Hello World" }- Set the following header params in response{ fname: John lname: Doe }Update the Hello Universe variantto return the following file and the file location should be hard coded.{ "message" : "Hello Universe"}Set the following cookie params in response{ customerId: 123456}Update the default handler to do the following:Add reading of query parameter 'fname' and 'lname' from the request.If the customer id is greater than 5 charactersreturn 'invalid id' as responseIf the customer id is less than or equal to 5 charactersreturn following response from the handler (NOT Using The File)Hello - fname lnameAdd a POST route /set/customerId and in default handler read the payload value and log it on console.{ "customerid": 123456}2. Start mock serverMake a REST call to /get/message with customer id greater than 5 characters and check the response is Invalid IdMake a REST call to /get/message with customer id equal to 5 characters and check the response to be Hello undefined undefinedMake a REST call to http://localhost:8000/get/message/12345?fname=John&lname=Doe and check the response to be Hello John DoeSwitch to Hello World variant and check the response is "message" : "Hello World" and use dev tools on Chrome browser to verify that the header params are set (fname: John and lname: Doe)Switch to Hello Universe variant and check the response is "message" : "Hello Universe" and use dev tools on Chrome browser to verify that the cookie is set (customerId: 123456)Make a post call to mock server at http://localhost:8000/set/customerId using Postman (or any other HTTP client) with the following data and verify that 12345 is logged on the console{ "customerId" : 12345}",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 201/Exercise"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-201-dynamic-urls": {
"title": "Dynamic URLs",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. How to create dynamic urls/get/customerInfo/{customerid}/{zipcode}2. Adding a dynamic URL in mock servermidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { reply('How to read the customer id :('); }});3. Reading dynamic URL parametersvar id = req.params.customerid;4. Using dynamic values to define responsemidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { var id = req.params.customerid; reply('Customer id is ' + id + ' :)'); }});5. Passing dynamic URL parameters from the Midway UITry to pass dynamic url parameters generated from Midway UI",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 201/Dynamic URLs"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-201-customizing-mocked-response": {
"title": "Customizing Mocked Response",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. Set custom headersmidway.route({ id: 'header', label: 'Custom Headers', path: '/set/headers', handler: function(req, reply) { reply({message: 'custom headers'}) .header('header1', 'test1') .header('header2', 'test2') .header('header3', 'test3') }}) midway.route({ id: 'header', label: 'Custom Headers', path: '/set/headers', handler: function (req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; midway.util.respondWithFile(this, reply, {headers: myHeaders}); }});2. Set custom cookiesmidway.route({ id: 'cookies', label: 'Custom Cookies', path: '/set/cookies', handler: function(req, reply) { reply({message: 'test'}) .state('cookie1', 'testCookie1') .state('cookie2', 'testCookie2') }}); midway.route({ id: 'cookies', label: 'Custom Cookies', path: '/set/cookies', handler: function (req, reply) { var cookies = [ {name: 'cookie1', value: 'testCookie1'}, {name: 'cookie2', value: 'testCookie2'}, ]; midway.util.respondWithFile(this, reply, {cookies: cookies}); }});3. Set CORS headersvar corsHeaders = { origin: ['*'], headers: ["Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"], credentials: true,} // Itemsmidway.route({ id: 'corsheaders', label: 'CORS', path: '/set/cors', config: { cors: corsHeaders }, handler: function(req, reply) { reply('cors headers set'); }});",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 201/Customizing Mocked Response"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-101-setting-and-installing-mock-server": {
"title": "Setting and Installing Mock Server",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. Pre-requisitesnode.js 4+ (npm is included in the package)2. Add mock dependency to package.json"dependencies": { "testarmada-midway": "^1.0.1"}3. Install mock dependency with npm installRun npm install command to install mock related dependencies.4. Add resources/endpoints.js and create ./resources/mocked-data directory to store the mock data.require('./endpoints');require('midway').start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, project: 'HelloMidway'});5. Add resources/run-mock-server-console.jsrequire('./endpoints');require('midway').start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, project: 'HelloMidway'});Please note that you will need to replace HelloMidway for key project field with your project name(without dashes).6. Add script to start mock server in package.json"scripts": { "lint": "eslint . --ext .js", "start-server": "node ./resources/run-mock-server-console.js"},7. Test mock server can be startednpm run start-server",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 101/Setting and Installing Mock Server"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-101-introduction": {
"title": "Introduction",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. What is Midway?We provide a mocking solution which can be leveraged to quickly stub the REST API responses that are used by your application during development or testing. The application points to the mock service host address instead of the live service, pre-recorded responses are then returned for various endpoints from the mock service. Since there is minimal logic when writing mock service, maintaining and development cost for mock service is minimal. Some of the major development pain-points addressed by the mocking solution are:Unstable servicesInconsistent DataTest against negative or unreal scenarios2. Architectural Explanation3. High Level Key FeaturesUI Interface: Mock service UI for manual testing/debugging.Test Reuse: Execute same test cases against mock or live service.Drop-And-Respond: Respond with a mocked data file based on the url route path automatically by dropping mocked data file in folder mapping to url path.Response Reuse: Ability to use same json response file and change data dynamically for mocked response for various variants.Test De-coupling: No coupling with test cases - Test cases are independent of mock implementation except that setting the desired response for the mock service (which has no impact if the test case is run against a live service).Common Utilities: Common utility methods are provided as part of this solution which allows quicker test development.HTTPS Support: HTTPS support for all the urls.Magellan/Nightwatch integration: Ability to use mocking service with Magellan tests.Parallel sessions: Support for single instance mock server for parallel processesSwagger integration: Automatic mock creator for web-services with swagger definition.Server states: Ability to mock server state.4. Mock TerminologyRoutesVariantsHandlerSetMockIdAdmin UIRespondWithFile",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 101/Introduction"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-101-introduction-to-variants": {
"title": "Introduction to Variants",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. What are variants?Variants allows to return a different data set for a given mocked route. Variants can be selected in the admin UI to determine what type of response a route should have. Routes are defined using the variant method on the Route object (returned by calling the route method). An object parameter is provided with the following attributesid: the variant id - used for the RESTful admin API and profile settingslabel: (optional) the variant label - used for display on the admin panelhandler: (optional) the HAPI route handler which provides the route responseVariants are useful because they allow you to test multiple scenarios that can happen with your route. Say, for example, you have a route exposing the ability to update a password. You might have several exceptional scenarios that you would want to test out (each could be a variant that you simply select to tell the route handler to use the appropriate response)the password was reset successfullythe password didn't pass validationthe old password wasn't entered correctlythe username doesn't existand so on...2. Default HandlerThe handler defined under route is the default handlermidway.route({ id: 'helloWorld', label: 'Hello World', path: '/helloWorld', method: 'GET', handler: function (req, reply) { reply('Hello World'); }});3. Creating a variantmidway.route({ id: 'message', label: 'Message', path: '/get/message', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { reply('Hello'); }}).variant({ id: 'hello', label: 'Hello World', handler: function (req, reply) { reply('Hello World'); }});4. Selecting a different variant to be returned from UIYou can select a different variant from admin UI to determine what type of response a route should have.5. Adding more variantsmidway.route({ id: 'message', label: 'Message', path: '/get/message', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { reply('Hello'); }}).variant({ id: 'hello', label: 'Hello World', handler: function (req, reply) { reply('Hello World'); }}).variant({ id: 'helloUniverse', label: 'Hello Universe', handler: function (req, reply) { reply('Hello Universe'); }});",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 101/Introduction to Variants"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-101-introduction-to-mocking-ui": {
"title": "Introduction to Mocking UI",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. Starting Mocking UITo start Mocking UI, after starting mock server navigate to http://localhost:8000/midway on your favorite browser.2. Navigating through Mocking UITry to navigate through Mocking UI to get better undertstanding of its functions.",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 101/Introduction to Mocking UI"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-101-exercise": {
"title": "Exercise",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. Create mock server with the followingAdd a GET route /get/message with default variant returning HelloAdd a variant that returns "Hello World"Add another variant that returns "Hello Universe"Add another GET route /get/numbers with default variant returning incremental values starting from 1Add a variant that returns even number starting from 2 in incrementsAdd another variant to return odd numbers starting from 1 in increments2. Start mock serverMake a REST call to /get/message and verify default variant returns 'Hello'Switch back and forth to other two variants and verify that you see 'Hello World' and 'Hello Universe' message respectively.Make a REST call to /get/numbers and verify default variant returns numbers in incremental orderSwitch back and forth to other two variants and verify that you see even and odd numbers in incremental order respectively.",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 101/Exercise"
},
"documentation-mocking-native-ios-javascript-training-guide-mocking-101-adding-routes-for-mocking": {
"title": "Adding Routes for Mocking",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. What REST APIs can be mocked?GETHEADPOSTPUTPATCHDELETEOPTIONS2. Add a route to be mocked in endpoints.jsmidway.route({ id: 'helloWorld', label: 'Hello World', path: '/helloWorld', method: 'GET', handler: function (req, reply) { reply('Hello World'); }});Now start mock server and hit http://localhost:8000/helloWorld3. Understanding route parametersid: Unique route idlabel: Description of the routepath: Path of the routemethod: HTTP methodhandler: Function which handles the request for the path4. Adding multiple routes to be mockedmidway.route({ id: 'helloUniverse', label: 'Hello Universe', path: '/helloUniverse', method: 'GET', handler: function (req, reply) { reply('Hello Universe'); }});Now start mock server and hit http://localhost:8000/helloUniverse",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/Mocking 101/Adding Routes for Mocking"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-401-state": {
"title": "State",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. What is state?State allows you to maintain state of your server, for example if a user is logged in or logged out. The mock server internally uses Hapi node server, which helps you return the state of the current application state. Within any response handler, use this.state('varName') to access an object stored in the state and this.state('varName', 'varValue') where varValue can be any type of object you want to set the state.2. How to set a state in mock server?midway.route({ path: '/api/login', label: 'LogIn', method: 'POST', handler: function(request, reply) { // now you can use this.state('loggedIn') in any route handler to see if the user has logged in this.state('loggedIn', true); reply().code(204); }});",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 401/State"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-401-starting-https-server-with-mock-server": {
"title": "Starting HTTPS server with Mock Server",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. Updating run-mock-server-console.js to enable HTTPSrequire('./endpoints');var fs = require('fs');var midway = require('testarmada-midway'); midway.start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, httpsPort: 4444, project: 'HelloMidway'});The default port for HTTPS is 44442. Starting mock server with HTTPS enabledOnce you add the above code, the mock server will provide the HTTPS and HTTPS support by default. Hence when the mock server starts up, you will see both the ports open. Note that the mock server auto generates the certificates (key.pem and cert.pem). If you want to provide your own key and certificate, you can provide it under the mocked data directory.",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 401/Starting HTTPS server with Mock Server"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-401-rest-apis": {
"title": "Rest APIs",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. Set VariantMethod : POSTSyntax : {host}:{port}/_admin/api/route/{routeId}Rest API : curl -H "Content-Type: application/json" -X POST -d '{"variant":"preorder"}' http://localhost:8000/_admin/api/route/getCollection?returnConfig=truemidway.route({ id: 'getCollection', label: 'Get Collection', path: '/product/grouping/api/collection/{collectionId}', variantLabel: 'default', handler: function(req, reply) { var response = getResponseData('/product/grouping/api/collection', 'default'); reply(response); }}).variant({ id: 'preorder', label: 'Get Pre-order Collection', handler: function (req, reply) { reply({message: 'hello pre-order'}); }});To get the config back as a response, add query parameter returnConfig=true as shown in example above2. Set Mock IdMethod : GETSyntax : {host}:{port}/_admin/api/midway/setMockId/{mockid}/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/setMockId/1234/default3. Get Mock IdMethod : GETSyntax : {host}:{port}/_admin/api/midway/getMockId/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/getMockId/default4. Reset Mock IdMethod : GETSyntax : {host}:{port}/_admin/api/midway/resetMockId/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/resetMockId/default5. Get Url CountMethod : GETSyntax : {host}:{port}/_admin/api/midway/getURLCount/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/getURLCount/default6. Reset Url CountMethod : GETSyntax : {host}:{port}/_admin/api/midway/resetURLCount/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/resetURLCount/default7. Re-set the state of Mock ServerMethod : POSTSyntax : {host}:{port}/_admin/api/state/resetRest API : curl -X POST http://localhost:8000/_admin/api/state/reset8. Register SessionMethod : GETSyntax : {host}:{port}/_admin/api/midway/registerSessionRest API : curl http://localhost:8000/_admin/api/midway/registerSession9. Get SessionsMethod : GETSyntax : {host}:{port}/_admin/api/midway/getSessionsRest API : curl http://localhost:8000/_admin/api/midway/getSessions10. Check SessionMethod : GETSyntax : {host}:{port}/_admin/api/midway/checkSession/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/checkSession/{sessionid}11. Close SessionMethod : GETSyntax : {host}:{port}/_admin/api/midway/closeSession/{sessionid}Rest API : curl http://localhost:8000/_admin/api/midway/closeSession/{sessionid}",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 401/Rest APIs"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-401-mocking-utility-methods": {
"title": "Mocking Utility Methods",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExercise1. RespondWithFile Utilitymidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }})Setting Codemidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400}); }})Custom File Locationmidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json'}); }})Setting Headersmidway.route({id: 'message',label: 'hello message',path: '/message',handler: function(req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json', headers: myHeaders});}});Setting Cookiesmidway.route({id: 'message',label: 'hello message',path: '/message',handler: function(req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; var cookies = [ {name: 'com.wm.customer', value: 'vz7.0b5c56'}, {name: 'CID', value: 'SmockedCID', options: {domain: 'domain', path: '/'}}, {name: 'anotherCookie', value: 'cookieValue'} ]; midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json', headers: myHeaders, cookies: cookies});}});Setting Delaymidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; var cookies = [ {name: 'com.wm.customer', value: 'vz7.0b5c56'}, {name: 'CID', value: 'SmockedCID', options: {domain: 'domain', path: '/'}}, {name: 'anotherCookie', value: 'cookieValue'} ]; midway.util.respondWithFile(this, reply, {code: 400, filePath: '../mocked-data/fileName.json', headers: myHeaders, cookies: cookies, delay: 1000}); }});Modifying Static JSON responseIf you have many variants for a REST end point and the mocked data for all variants can use the same JSON response with few changes to the values, than this feature is what you need. This feature allows you to dynamically change a JSON file before sending the response back from the mock server for the request. It removes the need of having one to one mapping of static JSON files with each variants.// Static Response JSON File{ "id": "1234", "name": "toothpaste", "details": [ { "flavor": "Mint 1", "Size": "10", "Size_Type": "ounce" }, { "flavor": "Mint", "Size": "10", "Size_Type": "ounce" } ]}// Sample code for substituting id from 1234 to 7777 and flavor from Mint to Mint 2 for second array element in routesmidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { var dataToChange = { 'id': '7777', 'details[1].flavor': 'Mint 2' } midway.util.respondWithFile(this, reply, {transpose: dataToChange}); }});// Dynamic Response JSON File returned from Mock service{ "id": "7777", "name": "toothpaste", "details": [ { "flavor": "Mint 1", "Size": "10", "Size_Type": "ounce" }, { "flavor": "Mint 2", "Size": "10", "Size_Type": "ounce" } ]}2. Logging utilityMidway exposes a logging utility which can be used to log datamidway.log.debug('This is debug Message');midway.log.info('This is info Message');midway.log.error('This is error Message');midway.log.warn('This is warn Message');midway.log.setLogLevel('debug');midway.log.getLogLevel();midway.log.resetLogLevel();// default level is INFO3. Responding with a specific variant in handlers (respondWithMockVariant)This function will respond with a variant on the main route handler. The variant passed in MUST be the variant on existing route.midway.util.respondWithMockVariant(this, 'variant', reply);The variant passed in MUST be the variant on existing route.midway.route({ id: 'respondWithVariant', label: 'Respond With Variant', path: '/respondWithVariant', variantLabel: 'Respond With Variant Main Route', handler: function (req, reply) { midway.util.respondWithMockVariant(this, 'variant', reply); // make sure that the variant exist in the same route. }}).variant({ id: 'variant', label: 'Respond With Variant Variant Route', handler: function (req, reply) { reply({'message': 'I am an example of respond_with_mock_variant instead of response of main route '}); }});4. GetUrlCountTo get URL count for all Rest APIs mocked by mock serverMidway API : midway.getURLCount("default");5. ResetUrlCountTo resets URL count to zeroMidway API : midway.resetURLCount("default");",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 401/Mocking Utility Methods"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-401-exercise": {
"title": "Exercise",
"content": "StateMocking Utility MethodsRest APIsStarting HTTPS server with Mock ServerExerciseUpdate the previous mock server with the following:Add a logg-in route api/loginAdd a log-out route api/logoutAdd a state variable loggedIn and set true/false value based on the above APIs.Update the get/message default handler to return the message Hello: fname lname if user is logged in by reading from the query parameters otherwise Hello: Guest is the customer Id is less than equal to 5 characters.Update the get/message Hello Universe variant to modify the file to following using transpose data based on if user is logged in or logged out- User Logged In{ message: fname lname}- User Logged Out{ message: Guest}Start mock serverHit get/message with customer id length <=5 and see you should get Hello: GuestSet the variant to Hello UniverseHit get/message with customer id length <=5 and see you should get message: GuestHit api/loginSet the variant to defaultHit http://localhost:8000/get/message/12345?fname=John&lname=Doe with customer id length <=5 and see you should get Hello: John Doe.Set the variant to Hello UniverseHit http://localhost:8000/get/message/12345?fname=John&lname=Doe with customer id length <=5 and see you should get message:John DoeHit api/logout and repeat 5 to 7.Create and install certificates to enable HTTPS in Midway.Update run-mock-server-console.js to enable https in mock server.Start mock server and navigate to https://localhost:4444/_admin and repeat 5 to 12 steps.",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 401/Exercise"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-301-setmockid": {
"title": "SetMockId",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. What is SetMockIdThis feature is very handy when you want to stub all the endpoints for a particular test without manually writing the paths for those endpoints. Generally applicable in scenarios where one page calls different endpoints according to test flows. You do not need to set variant or create variants for these endpoints. You will need to manually store the stubbed JSON files in the file structure location which are specified by your endpoints. The endpoints responses can be captured and stored under mocked data directory as a one time setup.2. How SetMockId works?ScenarioLets say your test case requires to mock two end points /api/message and /api/product/getStatus. These endpoints are called three times each. For the first end point you always want to return the same data (in json) while for the second endpoint you want to return the same data for the first and third call (in html) and a different data for the second call (in html).ImplementationCreate a folder under the mocked-data of your test directory (this folder name is configurable when you start your mock server by passing mockedDirectory option) by the name test1. Under this folder add the following files for your mocked response.api-message-GET.json - This will be returned for all the calls for the first endpoint with default response code 200api-product-getStatus-GET.html - This will be returned for all the calls for the second endpoint with default response code 200, except for the second and third call as it has its own fileapi-product-getStatus-GET-2.html - This will be returned for the second call for the second endpoint with default response code 200api-product-getStatus-GET-3-code-201.html - This will be returned for the third call for the second endpoint with response code 201Now set the setMockId either by mock api, UI or rest call to set to test1ExplanationThe underlying mock service automatically figures out the file extension so that you do not have to specify it. If you have the same file with multiple file extension than the following order is used:JSONHTMLTXTFirst file encountered of any other extensionOnce the midway.setMockId(“test1”) API is called, Midway only looks for the responses under the test1 folder. If it does not find the response, it will return 404 with the file name that it did not find. Midway internally keeps track of the number of times each individual endpoint is called after client.setMockId(“test1”) API is called and first looks for the file with count specific name such as api-message-GET-1.json, if it does not find the said file then it looks for the default file which is api-message-GET.json.3. Good To KnowIf setMockId is set, then custom file path in handlermidway.util.respondWithFile(this, reply, {filePath: ‘./message/GET/default.json’});and file based on URL path ./mocked-data/api/message/get/default.json are ignored for the mocked response. Here is the order followed for file lookup:SetMockIdCustom File Path for default or variants endpoints.File based on URL Path for default or variants endpoints.SetMockId does not work with in-line Handlermidway.route({ id: 'message', label: 'Message', path: '/get/message/{customerid}', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { var lname = req.query.lname; var fname = req.query.fname; var customerid = req.params.customerid; if (customerid.length > 5) { reply().code(400); } else { reply('Hello ' + fname + " " + lname); } }})",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 301/SetMockId"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-301-parallel-sessions": {
"title": "Parallel Sessions",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. What is parallel sessions and why it's needed?Parallel sessions allows you to run multiple instance of server virtually while running only one server. This is helpful when you are running multiple test cases which access the same routes but different variants as parallel sessions allow you to set different variants on same routes without conflicting. This saves CPU and RAM both as only one server is running instead of multiple.2. How Parallel Sessions works internally?3. How to add parallel sessions?To add parallel sessions, modify run-mock-server-console.js to add 'sessions' parameter.require('./endpoints');var midway = require('testarmada-midway');midway.start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, sessions: 2, project: 'HelloMidway'});You can also start or add sessions via command line argumentnode resources/run-mock-server-console.js --midwaySessions 2If you pass sessions = 2, there will be two parallel sessions along with one default session.4. Supported APIs for Parallel sessionsRegister SessionTo register sessions to be usedvar sessionId = midway.registerSession();Get SessionsTo get all the active sessionsvar activeSessions = midway.getSessions();Check SessionTo check the session status (Available or In-Use or invalid)var sessionStatus = midway.checkSession(sessionId);Close SessionTo de-register session for later usevar closeSession = midway.closeSession(sessionId);5. Using Parallel SessionsTo use a parallel session call the following api:curl http://localhost:8000/_admin/api/midway/registerSessionormidway.registerSession()and a session id will be returned.Append this sessionId to the mocked host address to use this parallel session. For ex: If your mock host server is http://localhost:8080 and your session id is 112233 then the mock server address for this parallel session will be http://localhost:8080/112233.6. Verifying parallel sessionsStart mock server with two sessions. Now go to the 'Message' route. You will see three routes for message, default and two for parallel sessions that you just added. Now for each route choose a different variant and hit the URL icon. You will see that each time you will get a different value though you are hitting the same route.7. Understanding the Midway UI with sessionsTry to go through Midway UI to understand sessions.",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 301/Parallel Sessions"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-301-exercise": {
"title": "Exercise",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExerciseUpdate the previous mock server with the following:Update the Hello World variant of 'get/message' request toRemove the header parametersReturn the file as before by using RespondWithFile without handlerUpdate the default handler to return ONLY code 400 if the customer id is greater than 5 charactersStart mock server and test Step 1Now add data for setMockId for /get/message and /get/number routes.Return the following for URL hit count 1/get/message{ "message" : 1}/get/number{ "number" : 1}Return the following for URL hit count 2/get/message{ "message" : 2}/get/number{ "number" : 2}Return the following for default/get/message{ "message" : "Undefined"}/get/number{ "number" : "Undefined"}Call API to setMockId to the folder name via Midway UIHit the rest endpoint /get/message and /get/number one time each and verify the response is "message" : 1 and "number" : 1 respectively.Hit the rest endpoint /get/message and /get/number once more and verify the response for second hit is "message" : 2 and "number" : 2 respectively.Hit the rest endpoint /get/message and /get/number one more time to verify that the response is "message" : "undefined" and "number" : "undefined" respectively.Call ResetMockId API via Midway UIHit the rest endpoint /get/message and /get/number once each and verify the response is based on the handler and not on SetMockId - You may have to add appropriate file based on the route path.Update run-mock-server-console.js to add two parallel sessions to the server.Now call GetSessionId to register a session using Midway UI.Now set Hello World and Hello Universe variant for get/message api for the two sessions Ids respectively.Now hit the server https://localhost:8000/sessionId/get/message for different session Ids and verify that you get different responses as per each variant.",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 301/Exercise"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-301-different-ways-of-returning-response-data": {
"title": "Different ways of returning response data",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. Returning only the codemidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { reply().code(400); }})2. Using RespondWithFile without handlermidway.route({ path: '/api/customer/getId', label: 'Get Customer Id', method: 'GET', }).respondWithFile();3. Returning static mocked data with a response codemidway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400}); }})",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 301/Different ways of returning response data"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-301-apis-for-setmockid": {
"title": "APIs for SetMockId",
"content": "Different ways of returning response dataSetMockIdAPIs for SetMockIdParallel SessionsExercise1. SetMockIdmidway.setMockId("1234", "default");2. GetMockIdmidway.getMockId("default");3. ResetMockIdmidway.resetMockId("default");",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 301/APIs for SetMockId"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-201-returning-response-from-a-file": {
"title": "Returning Response from a File",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. What does it mean?This feature allows you to respond with a data stored in a file instead of hard coding the response data in the routes definition. This way user does not have to change the response rather can just swap the file with different data.2. How it works?midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }});In the above setup, file needed for default route, which is /get/fromFile should be located at ./mocked-data/get/fromFile/GET/default.json3. What is mockedDirectory Path?Mocked directory path is the location to the base directory where all your mocked response file will be stored. This parameter is defined in run-mock-server-console.js file. It is defined at the start of mock server as shown in the code below:require('./endpoints-Midway-201');require('midway').start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, project: 'HelloMidway'});4. Automatic calculation of file locationThe path to the mocked data file is auto-calculated based on the route path. For variants, the name of the file should be changed from default to the variant name as shown below:midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }}).variant({ id: 'textData', label: 'Text Data', handler: function (req, reply) { midway.util.respondWithFile(this, reply); }})In the above example, mock server would look for ./resources/mocked-data/get/fromFile/GET/textData.txt file for the variant textData5. Providing custom path to the response fileA custom file path could also be provided for a mocked data file. to do so, use the following code:midway.route({ id: 'CustomResponseFile', label: 'Response From Custom Path', path: '/get/customFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {filePath: './custom.json'}); }})Midway will look for the file under MockedDirectory only but at ./resources/mocked-data/custom.json",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 201/Returning Response from a File"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-201-request-call-information": {
"title": "Request Call Information",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. Query ParametersLet's say you go to the following URL: http://localhost:8000/get/customerInfo/12345?ctype=new . To read the query parameter, do the following:var ctype = req.query.ctype;To run the above scenario, hit the following in any browser with Midway server running: http://localhost:8000/get/customerInfo/12345?ctype=new after updating the route tomidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { var id = req.params.customerid; var ctype = req.query.ctype; var replyString = 'Customer Type: ' + ctype + ' customer id: ' + id; reply(replyString); }});2. Header informationLet's say there is a header parameter 'name' with value 'John' is passed with the request. To read the testHeader parameter, do the following:var req = req.raw.req;var name = req.headers.name;To run the above scenario, use postman to make the following get call: http://localhost:8000/get/customerInfo/12345?ctype=new and add header 'name' with value 'John' after updating the route tomidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { var id = req.params.customerid; var ctype = req.query.ctype; var req = req.raw.req; var name = req.headers.name; var replyString = 'Customer Type: ' + ctype + ' customer id: ' + id + ' nameFromHeader: ' + name; reply(replyString); }});3. PayloadThe payload can be read using the following code://fname would be "Bob" if the posted body content (as JSON) was {"fname": "Bob"}var fname = req.payload.fname;To run the above scenario, use postman to make the following POST call: http://localhost:8000/payload and add payload {"fname": "Bob"} in the request.midway.route({ id: 'payload', label: 'Reading Payload', path: '/payload', method: 'POST', variantLabel: 'Payload', handler: function (req, reply) { var fname = req.payload.fname; reply(fname); }});4. Content TypesThe mock module is independent of content-types i.e. user can set any content type and mocking route is intercepted only based on the path defined in the mocked routes file.",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 201/Request Call Information"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-201-exercise": {
"title": "Exercise",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. Update the previous mock server with the followinga. Update the route /get/message to a dynamic URL which takes customer id as a parameter.b. Update the 'Hello World' variant to- return the following file with auto file location calculation.json { "message" : "Hello World" }- Set the following header params in response{ fname: John lname: Doe }Update the Hello Universe variantto return the following file and the file location should be hard coded.{ "message" : "Hello Universe"}Set the following cookie params in response{ customerId: 123456}Update the default handler to do the following:Add reading of query parameter 'fname' and 'lname' from the request.If the customer id is greater than 5 charactersreturn 'invalid id' as responseIf the customer id is less than or equal to 5 charactersreturn following response from the handler (NOT Using The File)Hello - fname lnameAdd a POST route /set/customerId and in default handler read the payload value and log it on console.{ "customerid": 123456}2. Start mock serverMake a REST call to /get/message with customer id greater than 5 characters and check the response is Invalid IdMake a REST call to /get/message with customer id equal to 5 characters and check the response to be Hello undefined undefinedMake a REST call to http://localhost:8000/get/message/12345?fname=John&lname=Doe and check the response to be Hello John DoeSwitch to Hello World variant and check the response is "message" : "Hello World" and use dev tools on Chrome browser to verify that the header params are set (fname: John and lname: Doe)Switch to Hello Universe variant and check the response is "message" : "Hello Universe" and use dev tools on Chrome browser to verify that the cookie is set (customerId: 123456)Make a post call to mock server at http://localhost:8000/set/customerId using Postman (or any other HTTP client) with the following data and verify that 12345 is logged on the console{ "customerId" : 12345}",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 201/Exercise"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-201-dynamic-urls": {
"title": "Dynamic URLs",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. How to create dynamic urls/get/customerInfo/{customerid}/{zipcode}2. Adding a dynamic URL in mock servermidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { reply('How to read the customer id :('); }});3. Reading dynamic URL parametersvar id = req.params.customerid;4. Using dynamic values to define responsemidway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}', method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { var id = req.params.customerid; reply('Customer id is ' + id + ' :)'); }});5. Passing dynamic URL parameters from the Midway UITry to pass dynamic url parameters generated from Midway UI",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 201/Dynamic URLs"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-201-customizing-mocked-response": {
"title": "Customizing Mocked Response",
"content": "Dynamic URLsRequest Call InformationCustomizing Mocked ResponseReturning Response from a FileExercise1. Set custom headersmidway.route({ id: 'header', label: 'Custom Headers', path: '/set/headers', handler: function(req, reply) { reply({message: 'custom headers'}) .header('header1', 'test1') .header('header2', 'test2') .header('header3', 'test3') }}) midway.route({ id: 'header', label: 'Custom Headers', path: '/set/headers', handler: function (req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; midway.util.respondWithFile(this, reply, {headers: myHeaders}); }});2. Set custom cookiesmidway.route({ id: 'cookies', label: 'Custom Cookies', path: '/set/cookies', handler: function(req, reply) { reply({message: 'test'}) .state('cookie1', 'testCookie1') .state('cookie2', 'testCookie2') }}); midway.route({ id: 'cookies', label: 'Custom Cookies', path: '/set/cookies', handler: function (req, reply) { var cookies = [ {name: 'cookie1', value: 'testCookie1'}, {name: 'cookie2', value: 'testCookie2'}, ]; midway.util.respondWithFile(this, reply, {cookies: cookies}); }});3. Set CORS headersvar corsHeaders = { origin: ['*'], headers: ["Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"], credentials: true,} // Itemsmidway.route({ id: 'corsheaders', label: 'CORS', path: '/set/cors', config: { cors: corsHeaders }, handler: function(req, reply) { reply('cors headers set'); }});",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 201/Customizing Mocked Response"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-101-setting-and-installing-mock-server": {
"title": "Setting and Installing Mock Server",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. Pre-requisitesnode.js 4+ (npm is included in the package)2. Add mock dependency to package.json"dependencies": { "testarmada-midway": "^1.0.1"}3. Install mock dependency with npm installRun npm install command to install mock related dependencies.4. Add resources/endpoints.js and create ./resources/mocked-data directory to store the mock data.require('./endpoints');require('midway').start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, project: 'HelloMidway'});5. Add resources/run-mock-server-console.jsrequire('./endpoints');require('midway').start({ host: "localhost", mockedDirectory: "./resources/mocked-data", port: 8000, project: 'HelloMidway'});Please note that you will need to replace HelloMidway for key project field with your project name(without dashes).6. Add script to start mock server in package.json"scripts": { "lint": "eslint . --ext .js", "start-server": "node ./resources/run-mock-server-console.js"},7. Test mock server can be startednpm run start-server",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 101/Setting and Installing Mock Server"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-101-introduction": {
"title": "Introduction",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. What is Midway?We provide a mocking solution which can be leveraged to quickly stub the REST API responses that are used by your application during development or testing. The application points to the mock service host address instead of the live service, pre-recorded responses are then returned for various endpoints from the mock service. Since there is minimal logic when writing mock service, maintaining and development cost for mock service is minimal. Some of the major development pain-points addressed by the mocking solution are:Unstable servicesInconsistent DataTest against negative or unreal scenarios2. Architectural Explanation3. High Level Key FeaturesUI Interface: Mock service UI for manual testing/debugging.Test Reuse: Execute same test cases against mock or live service.Drop-And-Respond: Respond with a mocked data file based on the url route path automatically by dropping mocked data file in folder mapping to url path.Response Reuse: Ability to use same json response file and change data dynamically for mocked response for various variants.Test De-coupling: No coupling with test cases - Test cases are independent of mock implementation except that setting the desired response for the mock service (which has no impact if the test case is run against a live service).Common Utilities: Common utility methods are provided as part of this solution which allows quicker test development.HTTPS Support: HTTPS support for all the urls.Magellan/Nightwatch integration: Ability to use mocking service with Magellan tests.Parallel sessions: Support for single instance mock server for parallel processesSwagger integration: Automatic mock creator for web-services with swagger definition.Server states: Ability to mock server state.4. Mock TerminologyRoutesVariantsHandlerSetMockIdAdmin UIRespondWithFile",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 101/Introduction"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-101-introduction-to-variants": {
"title": "Introduction to Variants",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. What are variants?Variants allows to return a different data set for a given mocked route. Variants can be selected in the admin UI to determine what type of response a route should have. Routes are defined using the variant method on the Route object (returned by calling the route method). An object parameter is provided with the following attributesid: the variant id - used for the RESTful admin API and profile settingslabel: (optional) the variant label - used for display on the admin panelhandler: (optional) the HAPI route handler which provides the route responseVariants are useful because they allow you to test multiple scenarios that can happen with your route. Say, for example, you have a route exposing the ability to update a password. You might have several exceptional scenarios that you would want to test out (each could be a variant that you simply select to tell the route handler to use the appropriate response)the password was reset successfullythe password didn't pass validationthe old password wasn't entered correctlythe username doesn't existand so on...2. Default HandlerThe handler defined under route is the default handlermidway.route({ id: 'helloWorld', label: 'Hello World', path: '/helloWorld', method: 'GET', handler: function (req, reply) { reply('Hello World'); }});3. Creating a variantmidway.route({ id: 'message', label: 'Message', path: '/get/message', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { reply('Hello'); }}).variant({ id: 'hello', label: 'Hello World', handler: function (req, reply) { reply('Hello World'); }});4. Selecting a different variant to be returned from UIYou can select a different variant from admin UI to determine what type of response a route should have.5. Adding more variantsmidway.route({ id: 'message', label: 'Message', path: '/get/message', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { reply('Hello'); }}).variant({ id: 'hello', label: 'Hello World', handler: function (req, reply) { reply('Hello World'); }}).variant({ id: 'helloUniverse', label: 'Hello Universe', handler: function (req, reply) { reply('Hello Universe'); }});",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 101/Introduction to Variants"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-101-introduction-to-mocking-ui": {
"title": "Introduction to Mocking UI",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. Starting Mocking UITo start Mocking UI, after starting mock server navigate to http://localhost:8000/midway on your favorite browser.2. Navigating through Mocking UITry to navigate through Mocking UI to get better undertstanding of its functions.",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 101/Introduction to Mocking UI"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-101-exercise": {
"title": "Exercise",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. Create mock server with the followingAdd a GET route /get/message with default variant returning HelloAdd a variant that returns "Hello World"Add another variant that returns "Hello Universe"Add another GET route /get/numbers with default variant returning incremental values starting from 1Add a variant that returns even number starting from 2 in incrementsAdd another variant to return odd numbers starting from 1 in increments2. Start mock serverMake a REST call to /get/message and verify default variant returns 'Hello'Switch back and forth to other two variants and verify that you see 'Hello World' and 'Hello Universe' message respectively.Make a REST call to /get/numbers and verify default variant returns numbers in incremental orderSwitch back and forth to other two variants and verify that you see even and odd numbers in incremental order respectively.",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 101/Exercise"
},
"documentation-mocking-native-android-javascript-training-guide-mocking-101-adding-routes-for-mocking": {
"title": "Adding Routes for Mocking",
"content": "IntroductionSetting and Installing Mock ServerAdding Routes for MockingIntroduction to Mocking UIIntroduction to VariantsExercise1. What REST APIs can be mocked?GETHEADPOSTPUTPATCHDELETEOPTIONS2. Add a route to be mocked in endpoints.jsmidway.route({ id: 'helloWorld', label: 'Hello World', path: '/helloWorld', method: 'GET', handler: function (req, reply) { reply('Hello World'); }});Now start mock server and hit http://localhost:8000/helloWorld3. Understanding route parametersid: Unique route idlabel: Description of the routepath: Path of the routemethod: HTTP methodhandler: Function which handles the request for the path4. Adding multiple routes to be mockedmidway.route({ id: 'helloUniverse', label: 'Hello Universe', path: '/helloUniverse', method: 'GET', handler: function (req, reply) { reply('Hello Universe'); }});Now start mock server and hit http://localhost:8000/helloUniverse",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/Mocking 101/Adding Routes for Mocking"
},
"documentation-functional-testing-rweb-javascript-training-guide-rweb-testing-remote-browser-testing": {
"title": "Remote browser testing",
"content": "PrerequisitesBuilt-in browser testingRemote browser testingRemote browser testingDon’t have a desired browser in your local? No worry, you can use the following executors for remote test.magellan-saucelabs-executor: Drive tests on Saucelabsmagellan-testobject-executor: Drive tests on TestObjectmagellan-browserstack-executor: Drive tests on Browserstackmagellan-seleniumgrid-executor: Drive tests in selenium gridEnable an executorTo do the remote browser test, you need to enable an executor:Install the wanted executor via npm install or add it into your package.json file.E.g. install from npm install:npm install testarmada-magellan-saucelabs-executor --saveAdd following code in your magellan.json{ "executors": [ "testarmada-magellan-saucelabs-executor" ], "strategy_bail": "testarmada-magellan-early-bail-strategy"}Please note: Some executors need specific configuration to be functional. Please refer to the README.md in executor’s repo for detail configuration.Run tests with multiple executorsMagellan allows to run tests with one or more executors at the same time. This is done by passing a specific command line argument to magellan.For local tests, after enable magellan-local-executor# to run test in Chrome--local_browser chrome# to run test in both Chrome and Firefox--local_browsers chrome, firefoxQuizCan you enable both magellan-local-executor and magellan-saucelabs-executor for your test? and run test in local Chrome and Chrome 60 on Sauce Labs?",
"url": "/documentation/Functional Testing/rWeb/JAVASCRIPT/Training Guide/rWeb Testing/Remote browser testing"
},
"documentation-functional-testing-rweb-javascript-training-guide-rweb-testing-prerequisites": {
"title": "Prerequisites",
"content": "PrerequisitesBuilt-in browser testingRemote browser testingPrerequisitesEven though we’ve included everything that is needed in the package.json file, it’s always good to have an idea on which dependency is a must for your desktop browser test.The following dependencies are required in the package.json.{ "dependencies": { "nightwatch": "^0.9.11", "selenium-server": "^3.1.0" }}magellan-local-browser is also required for your local test.{ "dependencies": { "testarmada-magellan-local-executor": "^2.0.0" }}Depending on which browser you want to test, you need to include specific browser driver in your package.json. E.g. If you want to run your tests on both Chrome and Firefox:{ "dependencies": { "chromedriver": "^2.27.2", "geckodriver": "^1.4.0" }}Then, you need to add these drivers in the nightwatch.json file. E.g. "cli_args": { "webdriver.chrome.driver": "./node_modules/chromedriver/lib/chromedriver/chromedriver", "webdriver.gecko.driver": "./node_modules/geckodriver/bin/geckodriver" }",
"url": "/documentation/Functional Testing/rWeb/JAVASCRIPT/Training Guide/rWeb Testing/Prerequisites"
},
"documentation-functional-testing-rweb-javascript-training-guide-rweb-testing-built-in-browser-testing": {
"title": "Built-in browser testing",
"content": "PrerequisitesBuilt-in browser testingRemote browser testingBuilt-in browser testingThe sample project has some pre-configured browsers that you can use via --local_browser command.For example, the following command triggers your test in the local Chrome.DPRO=local ./node_modules/.bin/magellan --local_browser chrome --test tests/demo-simple.js --serial --max_test_attempts 1Full list of built in browser can be found at test_settings part in conf/nightwatch.json fileTo run test with a new browser, you can just create a new entry in test_settings part",
"url": "/documentation/Functional Testing/rWeb/JAVASCRIPT/Training Guide/rWeb Testing/Built-in browser testing"
},
"documentation-functional-testing-rweb-javascript-training-guide-tests-framework-page-object-properties": {
"title": "Page Object properties",
"content": "About the testsPage Object propertiesPage Object propertiesWe have pages, elements, sections and commands properties under ./lib directory. They are the page object properties required by nightwatch.js. For more information on how to define them please refer this.page is the highest level page object property, defined base on one particular page.One page can have multiple sections.It is useful to define sections of a page. Sections do two things:Provide a level of namespacing under the pageProvide element-level nesting so that any element defined within a section is a descendant of its parent section in the DOMelements are the places that your tests will interact with through commands and assertions on each page. This is made simple using the elements property so that all your elements are defined in a single place.You can add commands to your page object using the commands property. This is a useful way to encapsulate logic about the page that would otherwise live in a test, or multiple tests.command will be called in the context of the page or section where it is defined.",
"url": "/documentation/Functional Testing/rWeb/JAVASCRIPT/Training Guide/Tests Framework/Page Object properties"
},
"documentation-functional-testing-rweb-javascript-training-guide-tests-framework-about-the-tests": {
"title": "About the tests",
"content": "About the testsPage Object propertiesWe recommend using Page Objects methodologyThe Page Objects methodology is a popular pattern to write end-to-end tests by wrapping the pages or page fragments of a web app into objects. To know more about it, please read this.About the testsFor our sample framework:Create a separate folder tests for tests in your project. Each file inside it will be loaded as a test.All the tests should extend testarmada-nightwatch-extra/lib/base-test-class, which passes certain information, such as selenium session information and test result.You can override before(), beforeEach(), afterEach() and after() method or add your own methods in your base test.A test can have multiple steps if needed, e.g.:const Test = require("../lib/base-test");module.exports = new Test({ tags: ["pageobject", "web"], "Load demo first page": function(client) { const df = client.page["demo-first"](); df .navigate() .api.resizeWindow(1200, 800); }, "Verify all cities on first page": function(client) { client .page["demo-first"]() .assert.elContainsText("#tokyo", "Tokyo") .assert.elContainsText(".city:eq(1) p:eq(1)", "Europe"); }, "Jump to demo second page": function(client) { client .page["demo-first"]() .jumpToSecondDemo(); }});Each test should have some tags, this will make it easier to group tests when execute.",
"url": "/documentation/Functional Testing/rWeb/JAVASCRIPT/Training Guide/Tests Framework/About the tests"
},
"documentation-functional-testing-rweb-javascript-training-guide-setup-setup-and-run-demo-tests-locally-and-on-saucelabs": {
"title": "Setup and run demo tests locally and on SauceLabs",
"content": "PrerequisitesSetup and run demo tests locally and on SauceLabsSetupPlease fork from boilerplate project and use git clone to have a local copy. Then run following commandsnpm installRun demo test locally:npm run testYou should see the runner magellan open up 2 Chrome windows at once, and the results of the two tests are aggregated in the console.Run demo test on Sauce Labs:npm run test:saucelabsGo to SauceLabs, after log in, you should be able to view your tests running at Dashboard. The tests are using Chrome60 browser on Windows 10.",
"url": "/documentation/Functional Testing/rWeb/JAVASCRIPT/Training Guide/Setup/Setup and run demo tests locally and on SauceLabs"
},
"documentation-functional-testing-rweb-javascript-training-guide-setup-prerequisites": {
"title": "Prerequisites",
"content": "PrerequisitesSetup and run demo tests locally and on SauceLabsMost of you must already know some about web automation. In this training series, we will show you how to leverage Test Armada tools to make end-to-end tests easy, reliable, and massively parallel distributing tests across available resources both locally and remotely.PrerequisitesHostname mapping and open certain portsPlease add the following hostname mapping in the /etc/hosts file127.0.0.1 dev.walmart.comDemo test will use ports range [12000, 12010], please make sure your machine allows those portsInstall nvmWe recommend using nvm to manage your node and npm version. The sample project recommends [email protected] and above, [email protected] and above.nvm install 6.11.2nvm use 6.11.2Apply SauceLabs credentials (username and api-key)The demo tests can be executed on SauceLabs. To use it, please make sure you have:SauceLabs accountHave the following credentials set up in ~/.bashrc fileexport SAUCE_CONNECT_VERSION=4.4.11export SAUCE_USERNAME=${YOUR_SAUCE_NAME}export SAUCE_ACCESS_KEY=${YOUR_SAUCE_API_TOKEN}Install Chrome browser, if you don't have it yet",
"url": "/documentation/Functional Testing/rWeb/JAVASCRIPT/Training Guide/Setup/Prerequisites"
},
"documentation-functional-testing-rweb-javascript-training-guide-magellan-magellan-usage": {
"title": "Magellan usage",
"content": "Magellan usageConfigure test profilesMagellan is a massively parallel test runner. By distributing tests across available CPU cores, Magellan blazes through long test suites in a fraction of the time, aggregating results in one friendly report.There are two ways to tell magellan how you want to scale your tests:Via Command Line ArgumentsAll command line arguments of magellan and its components (executors, reporters and plugins) that are enabled can be listed out by running following command:./node_modules/.bin/magellan --helpE.g. Run tests with 30 workers, 5 retry attempts per failed test:./node_modules/.bin/magellan --max_workers 30 --max_test_attempts 5Via magellan.json FileAll command line arguments of magellan can be placed into magellan.json. You can copy the key value pair straightly into it.For example,./node_modules/.bin/magellan --max_workers 30Is equal to this in magellan.json file:{ "max_workers": 30}Configuration NotesIf a configuration exists in both magellan.json and command line arguments, the one in magellan.json will take effect.Magellan searches magellan.json in your repo root by default. If you put it in a different folder, make sure to tell where it is by:./node_modules/.bin/magellan --config ${PATH_TO_MAGELLAN.JSON}Quick Reference Guide for Command-Line UseBy default, magellan will run your test suite the fastest way possible, in parallelYou can also run it serially (one at a time) by using --serial optionYou can view detailed debug info in --serial mode, with --debug optionTo control which tests to run, could use --tag, --tags option#Specify one tag:$ magellan --tag=smoke#Specify multiple tags:$ magellan --tags=smoke,webTo limit the tests by a file path prefix, use the --group optionTo run one specific test, use the --test flag with a path to the test file",
"url": "/documentation/Functional Testing/rWeb/JAVASCRIPT/Training Guide/Magellan/Magellan usage"
},
"documentation-functional-testing-rweb-javascript-training-guide-magellan-configure-test-profiles": {
"title": "Configure test profiles",
"content": "Magellan usageConfigure test profilesConfigure test profilesThere are two ways to configure test profilesVia --profile command line argumentMagellan can retrieve test profile information from an URL (to your hosted test profile).The hosted test profile file needs to follow the format of:{ "profiles": { "microsoftedge": [{ "browser": "MicrosoftEdge_16_Windows_10_Desktop", "resolution": "1280x1024", "executor": "sauce" }], "tier-one-browsers": [{ "browser": "MicrosoftEdge_16_Windows_10_Desktop", "resolution": "1280x1024", "executor": "sauce" }, { "browser": "chrome_latest_Windows_10_Desktop", "resolution": "1280x1024", "executor": "sauce" } ] }}Magellan can read and resolve the hosted profile by the following command:./node_modules/.bin/magellan --profile http://some.host#microsoftedgeYou can add as many test profiles as your need in the hosted file. Magellan is able to read more test profiles via:./node_modules/.bin/magellan --profile http://some.host#microsoftedge,firefox57Or put multiple test profiles into one collection, such as tier-one-browsers in the above sample. To call it:./node_modules/.bin/magellan --profile http://some.host#tier-one-browsersVia magellan.json fileMagellan.json file is using the same test profile format as the hosted test profile file.To use it:./node_modules/.bin/magellan --profile tier-one-browsers",
"url": "/documentation/Functional Testing/rWeb/JAVASCRIPT/Training Guide/Magellan/Configure test profiles"
},
"documentation-functional-testing-native-ios-javascript-training-guide-ios-automation-native-app-locators": {
"title": "Native app locators",
"content": "Desired CapabilitiesNative app locatorsNative app locatorsTo find the native app locators, there is a handy tool:Appium DesktopIt's a GUI wrapper around the Appium server, comes with an Inspector, which enables you to check out the hierarchy of your app.",
"url": "/documentation/Functional Testing/Native iOS/JAVASCRIPT/Training Guide/iOS Automation/Native app locators"
},
"documentation-functional-testing-native-ios-javascript-training-guide-ios-automation-desired-capabilities": {
"title": "Desired Capabilities",
"content": "Desired CapabilitiesNative app locatorsAfter we understand the tests framework, we can start to take a closer look on how native iOS app automation worksUnderlying we are using Appium to drive native iOS app automationMost concepts are similar for web and app automations, a few things maybe new to people who come from web automation world:Desired CapabilitiesDesired capabilities are a set of keys and values (i.e., a map or hash) sent to the Appium server to tell the server what kind of automation session we're interested in starting up.There are various capabilities which can modify the behavior of the server during automation.For example, we could set the platformName capability to iOS to tell Appium that we want an iOS session, rather than an Android one. See the capabilities doc for the complete list of capabilities available for Appium.For our sample repo, Desired Capabilities are defined either in profiles in magellan.json file or ./conf/nightwatch.json file. You can specify to use which one in your command line.For example, in your command, you can specify it via --profile appium-ios-app, which is defined in magellan.json file.s",
"url": "/documentation/Functional Testing/Native iOS/JAVASCRIPT/Training Guide/iOS Automation/Desired Capabilities"
},
"documentation-functional-testing-native-ios-javascript-training-guide-trouble-shooting-trouble-shooting-tips": {
"title": "Trouble shooting tips",
"content": "Trouble shooting tipsTrouble shooting tipsJava version errorException in thread "main" java.lang.UnsupportedClassVersionError: org/openqa/grid/selenium/GridLauncherV3 : Unsupported major.minor version 52.0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800)...Tips: Please check your java version (java -version), you should use java 1.8. You can download it here.Some general trouble shooting tips for Appium iOS app automation:When run simulator test, please sure the accessibility helper is turned off in your Settings appMake sure the app is compiled for the simulator (or real device) as appropriate (e.g. in debug mode for the simulator), or you might get a posix spawn error.If this is the first time you've run Appium, make sure to authorize the use of Instruments. See the UIAutomation Driver doc.Tests on iOS may exhibit symptoms similar to a memory leak including sluggish performance or hangs. If you experience this problem, it's likely due to a known issue with NSLog. One option is to remove NSLog from your code.Sometimes iOS UI elements become invalidated milliseconds after they are found. This results in an error that looks like (null) cannot be tapped. Sometimes the only solution is to put the finding-and-clicking code in a retry block.",
"url": "/documentation/Functional Testing/Native iOS/JAVASCRIPT/Training Guide/Trouble Shooting/Trouble shooting tips"
},
"documentation-functional-testing-native-ios-javascript-training-guide-tests-framework-understand-the-tests-framework": {
"title": "Understand the tests framework",
"content": "Understand the tests frameworkTests framework structureWhere to find mobile commandsWhen look at commands in page files, e.g. setMobileElValue() may look new to you. Those mobile commands are defined in ./node_modules/testarmada-nightwatch-extra/lib/commands/mobile.Assertions, e.g. mobileElAttrContains(), are defined in ./node_modules/testarmada-nightwatch-extra/lib/assertions/mobile.To use those mobile commands and assertions, need to add the following lines in nightwatch.json file: "custom_commands_path": [ "./node_modules/testarmada-nightwatch-extra/lib/commands/mobile" ], "custom_assertions_path": [ "./node_modules/testarmada-nightwatch-extra/lib/assertions/mobile" ],You can also add your customized commands into folder ./lib/custom_commands, to increase code reusability. And please remember to add the path to nightwatch.json file, e.g. "custom_commands_path": [ "./node_modules/testarmada-nightwatch-extra/lib/commands/mobile", "./lib/custom_commands" ],",
"url": "/documentation/Functional Testing/Native iOS/JAVASCRIPT/Training Guide/Tests Framework/Understand the tests framework"
},
"documentation-functional-testing-native-ios-javascript-training-guide-setup-setup-ios-app-test-on-local-machine": {
"title": "Setup iOS app test on local machine",
"content": "Setup iOS app test on local machineSetup iOS app test on Sauce LabsNew to native iOS app testing? No worry, you don’t need to know much to set it up. Let's get your first native iOS app test up and running in a couple of minutes.Setup iOS app test on local machinePrerequisites:Install Xcode 9.2Install Node.js >= v4.x.xInstall npm. Check that you have at least npm version 3 or above (required by [email protected]):$ npm --version# If not, install npm3$ npm install -g npm@3Please map dev.walmart.com to 127.0.0.1 in your host fileSetup Steps:Get the sample code and install the node package dependencies:# Create a workspace and get the smaple code$ git clone [email protected]:TestArmada/boilerplate-nightwatch.git$ cd boilerplate-nightwatch$ npm install$ npm install [email protected]$ npm install wdVerify all the required items are setup properly by running appium-doctor:# install appium-doctor (may require sudo)$ npm install appium-doctor -g# check that all iOS dependencies are set up correctly$ appium-doctor --iosGet a developer build of the application you want to test, put it under ./app folder, for example rename .app and put it as ./app/AUT.app.Please make sure you have iPhone 8, iOS 11.2 simulator before execute the sample test.Put following entry in your nightwatch.json"appiumiosapp": { "skip_testcases_on_fail": true, "desiredCapabilities": { "app": "./app/AUT.app", "appiumVersion": "1.7.2", "automationName": "XCUITest", "platformName": "iOS", "platformVersion": "11.2", "deviceName": "iPhone 8", "waitForAppScript": "true", "browserName": "" }, "selenium": { "start_process": false }, "appium": { "start_process": true, "fullReset": true } }If you would like to try out some different simulators, please modify the appiumiosapp part in .conf/nightwatch.json file.Add a test app.test.js under ./tests folder, it can be as simple as followingvar Test = require("testarmada-nightwatch-extra/lib/base-test-class");module.exports = new Test({ "Load demo page": function (client) { console.log('yeah'); }});Try the sample test:./node_modules/.bin/magellan --config magellan.json --local_browser appiumiosapp --test tests/app.test.js --serial --max_test_attempts 1You should see iOS simulator open, your app open, close and simulator close.If you don't have Saucelabs credential , please remove this line in ./magellan.json file for now. We'll get back to Saucelabs setup in next section."testarmada-magellan-saucelabs-executor"",
"url": "/documentation/Functional Testing/Native iOS/JAVASCRIPT/Training Guide/Setup/Setup iOS app test on local machine"
},
"documentation-functional-testing-native-ios-javascript-training-guide-setup-setup-ios-app-test-on-sauce-labs": {
"title": "Setup iOS app test on Sauce Labs",
"content": "Setup iOS app test on local machineSetup iOS app test on Sauce LabsSetup iOS app sample test on Sauce LabsOpen terminal: (or add them into .bash_profile)$ export SAUCE_USERNAME=${USERNAME}$ export SAUCE_ACCESS_KEY=${ACCESSKEY}Zip ./app/AUT.app to ./app/AUT.zipUpload the testing iOS app to Sauce Labs# Upload Walmart app to SauceLabs, and name it: Walmart_app.zip$ curl -u ${SAUCE_USERNAME}:${SAUCE_ACCESS_KEY} -X POST "http://saucelabs.com/rest/v1/storage/${SAUCE_USERNAME}/AUT.zip?overwrite=true" -H "Content-Type: application/octet-stream" --data-binary @./app/AUT.zipAdd following content under profiles in magellan.json"appium-ios-app": [ { "browser": "iphone_10_3_iOS_iPhone_7_Simulator", "orientation": "portrait", "appium": { "app": "sauce-storage:AUT.zip", "appiumVersion": "1.6.5", "automationName": "XCUITest", "sendKeyStrategy": "setValue", "waitForAppScript": "true", "locationServicesAuthorized": "false", "locationServicesEnabled": "true" } } ]To run tests on Saucelabs, use command:./node_modules/.bin/magellan --config magellan.json --profile appium-ios-app --test tests/app.test.js --serial --max_test_attempts=1You can view your tests running at: https://saucelabs.com/beta/dashboard/tests. You should see an iOS simulator open, your app open, close and simulator close.",
"url": "/documentation/Functional Testing/Native iOS/JAVASCRIPT/Training Guide/Setup/Setup iOS app test on Sauce Labs"
},
"documentation-functional-testing-native-android-javascript-training-guide-tests-framework-tests-framework-structure": {
"title": "Tests framework structure",
"content": "Execution commandsTests framework structureTests framework structureWhere to find mobile commands and assertionsWhen look at commands in page files, e.g. clickMobileEl() may look new to you. Those mobile commands are defined in ./node_modules/testarmada-nightwatch-extra/lib/commands/mobileAssertions, e.g. mobileElAttrContains(), are defined in ./node_modules/testarmada-nightwatch-extra/lib/assertions/mobileTo use those mobile commands and assertions, need to add the following lines in nightwatch.json file: "custom_commands_path": [ "./node_modules/testarmada-nightwatch-extra/lib/commands/mobile" ], "custom_assertions_path": [ "./node_modules/testarmada-nightwatch-extra/lib/assertions/mobile" ],You can also add your customized commands into folder ./lib/custom_commands, to increase code reusability. And please remember to add the path to nightwatch.json file, e.g. "custom_commands_path": [ "./node_modules/testarmada-nightwatch-extra/lib/commands/mobile", "./lib/custom_commands" ],",
"url": "/documentation/Functional Testing/Native Android/JAVASCRIPT/Training Guide/Tests Framework/Tests framework structure"
},
"documentation-functional-testing-native-android-javascript-training-guide-tests-framework-execution-commands": {
"title": "Execution commands",
"content": "Execution commandsTests framework structureExecution commandsAfter getting your tests up and running, you probably have tons of questions regarding how this work, let’s start with the command that we are using to get the tests running in local, which is:./node_modules/.bin/magellan --config magellan.json --local_browser appiumandroidapp --test tests/app.test.js --serial Commands parameters --test , --serial, --config, etc are all magellan arguments. To find all magellan command line arguments and the usages:./node_modules/.bin/magellan --helpMagellan is part of the functional JS TDK, and it is designed for running tests in massive scale.Following is an example that telling magellan to run tests with 30 workers, 5 retry attempts per failed test./node_modules/.bin/magellan --max_workers 30 --max_test_attempts 5--local_browser appiumandroidapp tells tests to use testarmada-magellan-local-executor . It loads Desired Capabilities from nightwatch.json.For our sample here, it will load appiumandroidapp desired capability from nightwatch.json file:To know more about Desired Capability, please read the next training section - Android Automation.Executor - acts as a middle layer between magellan and test framework to drive test run (via framework) based on a specific need (differentiated by executing environments).For local emulator test, you need to enable testarmada-magellan-local-executor in the magellan.json file.For remote emulator test, e.g. on SauceLabs, need to enable testarmada-magellan-saucelabs-executor in the magellan.json file.",
"url": "/documentation/Functional Testing/Native Android/JAVASCRIPT/Training Guide/Tests Framework/Execution commands"
},
"documentation-functional-testing-native-android-javascript-training-guide-setup-setup-android-app-test-on-local-machine": {
"title": "Setup Android app test on local machine",
"content": "PrerequisitesSetup Android app test on local machineSetup Android app test on SauceLabsRun Android app test in local emulatorGet the sample code and install the node package dependencies:# Create a workspace and get the smaple code$ git clone [email protected]:TestArmada/boilerplate-nightwatch.git$ cd boilerplate-nightwatch$ npm install$ npm install [email protected] all the required items are setup properly by running appium-doctor (only needed for the first time using):# install appium-doctor (may require sudo)$ npm install appium-doctor -g# check that all Android dependencies are set up correctly$ appium-doctor --androidGet a developer build of the application you want to test, put it under ./app folder, for example, rename .apk and put it as ./app/AUT.apkLaunch the a71_API_25 AVD in the emulatorPut following entry in your nightwatch.json"appiumandroidapp": { "skip_testcases_on_fail": true, "desiredCapabilities": { "app": "./app/AUT.apk", "appiumVersion": "1.7.2", "platformName": "Android", "platformVersion": "7.1.1", "deviceName": "a71_API_25" }, "selenium": { "start_process": false }, "appium": { "start_process": true, "fullReset": true }}Add a test app.test.js under ./tests folder, it can be as simple as followingvar Test = require("testarmada-nightwatch-extra/lib/base-test-class");module.exports = new Test({ "Load demo page": function (client) { console.log('yeah'); }});Try the sample test:./node_modules/.bin/magellan --config magellan.json --local_browser appiumandroidapp --test tests/app.test.js --serial --max_test_attempts 1You should see Android emulator open, your app open, close and simulator close.If you don't have Saucelabs credential , please remove following line in ./magellan.json file for now. We'll get back to Saucelabs setup in next section."testarmada-magellan-saucelabs-executor"Please note: the AVD_NAME may different from the AVD manager you see from Android Studio, you can find the right name from the following command:${ANDROID_HOME}/platform-tools/emulator -list-avdsTo know more about emulator commands, please read this.",
"url": "/documentation/Functional Testing/Native Android/JAVASCRIPT/Training Guide/Setup/Setup Android app test on local machine"
},
"documentation-functional-testing-native-android-javascript-training-guide-setup-setup-android-app-test-on-saucelabs": {
"title": "Setup Android app test on SauceLabs",
"content": "PrerequisitesSetup Android app test on local machineSetup Android app test on SauceLabsRun Android app test on SauceLabsOpen terminal: (or add them into .bash_profile)$ export SAUCE_USERNAME=${USERNAME}$ export SAUCE_ACCESS_KEY=${ACCESSKEY}Upload ./app/AUT.apk to SauceLabs via following curl$ curl -u ${SAUCE_USERNAME}:${SAUCE_ACCESS_KEY} -X POST "http://saucelabs.com/rest/v1/storage/${SAUCE_USERNAME}/AUT.apk?overwrite=true" -H "Content-Type: application/octet-stream" --data-binary @./app/AUT.apkAdd following content under profiles in magellan.json"appium-android-app": [{ "browser": "Android_GoogleAPI_Emulator_Android_7_1_Android", "orientation": "portrait", "appium": { "app": "sauce-storage:AUT.apk", "platformName": "Android", "appiumVersion": "1.7.2", "fullReset": "true", "noReset": "false" } }Run the Android sample app test on SauceLabs./node_modules/.bin/magellan --nightwatch_config conf/nightwatch.json --profile appium-android-app --test tests/app.test.js --max_test_attempts=1You can view your tests running at: https://saucelabs.com/beta/dashboard/tests. You should see an Android emulator open, your app open, close and simulator",
"url": "/documentation/Functional Testing/Native Android/JAVASCRIPT/Training Guide/Setup/Setup Android app test on SauceLabs"
},
"documentation-functional-testing-native-android-javascript-training-guide-setup-prerequisites": {
"title": "Prerequisites",
"content": "PrerequisitesSetup Android app test on local machineSetup Android app test on SauceLabsNew to Android app automation testing? No worry, you don’t need to know much to set it up. Let's get your first Android app test up and running in a couple of minutes.Prerequisites:Install latest Android StudioUpdate the following through Tools > SDK Manager:SDK Platforms: Download Android 7.1.1 (Nougat)Expand package details and include Google APIs Intel x86 Atom_64 System ImageSDK Tools: Update Android SDK Build-Tools, Android Emulator, Android SDK Platform-Tools, Android SDK Tools, Intel x86 Emulator AcceleratorCreate this Android Virtual Device (AVD):Download a71_device.xmlGo to Tools > AVD Manager in Android StudioClick on Create Virtual DeviceClick on Import Hardware ProfilesSelect the a71_device.xml fileRefresh page, select a71 device profile, and click NextClick on x86 Images tabSelect Nougat x86_64 Android 7.1.1 (Google APIs) (download may be required), and click NextSet AVD Name as a71_API_25, and click FinishInstall Node.js >= v4.x.xInstall npm. Check that you have at least npm version 3 or above (required by [email protected]):$ npm --version# If not, install npm3$ npm install -g npm@3",
"url": "/documentation/Functional Testing/Native Android/JAVASCRIPT/Training Guide/Setup/Prerequisites"
},
"documentation-functional-testing-native-android-javascript-training-guide-android-automation-native-android-locators": {
"title": "Native Android locators",
"content": "Desired CapabilitiesNative Android locatorsNative Android app locatorsTo find native Android app locators, there is a handy tool:Appium DesktopIt's a GUI wrapper around the Appium server, comes with an Inspector, which enables you to check out the hierarchy of your app.",
"url": "/documentation/Functional Testing/Native Android/JAVASCRIPT/Training Guide/Android Automation/Native Android locators"
},
"documentation-functional-testing-native-android-javascript-training-guide-android-automation-desired-capabilities": {
"title": "Desired Capabilities",
"content": "Desired CapabilitiesNative Android locatorsDesired CapabilitiesAfter we understand the tests framework, we can start to take a closer look on how Android app automation worksUnderlying we are using Appium to drive native Android app automationMost concepts are similar for web and app automations, a few things maybe new to people who come from web automation world:Desired CapabilitiesDesired capabilities are a set of keys and values (i.e., a map or hash) sent to the Appium server to tell the server what kind of automation session we're interested in starting up.There are various capabilities which can modify the behavior of the server during automation.For example, we could set the platformName capability to Android to tell Appium that we want an Android session, rather than an iOS one. See the capabilities doc for the complete list of capabilities available for Appium.For our sample repo, Desired Capabilities are defined either in profiles in magellan.json file or in ./conf/nightwatch.json file. You can specify to use which one in your command line.For example, in your command, you can specify it via --profile appium-ios-app, which means look up desired capability defined in profile style in magellan.json file.It is highly recommended to set the appPackage and appActivity capabilities in order to let Appium know exactly which package and activity should be launched for your application. Otherwise, Appium will try to determine these automatically from your app manifest. E.g. "appium-android-app": [ { "browser": "Android_GoogleAPI_Emulator_Android_7_1_Android", "orientation": "portrait", "appium": { "app": "sauce-storage:AUT.apk", "platformName": "Android", "appiumVersion": "1.7.2", "fullReset": "true", "noReset": "false", "appActivity": "com.yourcompany.android.main.MainActivity", "appWaitActivity": "com.yourcompany.android.main.AnotherActivity" } } ],",
"url": "/documentation/Functional Testing/Native Android/JAVASCRIPT/Training Guide/Android Automation/Desired Capabilities"
},
"documentation-performance-testing-rweb-declarative-introduction": {
"title": "Introduction",
"content": "SummaryAs a front end engineer, performance of your application becomes an essential measurement for your application to succeed. With evolving technologies and user-centric apps, it becomes very important to measure performance of your app before it gets released. This is where our tool can help you to measure the performance of the app at every phase of your release cycles.The performance measurement toolThe client side performance measurement tool is based on Sitespeed and is currently serving Web and mWeb interfaces. We have plans to roll out client side performance testing for native apps (android and iOS) soon.Our test runner is a self-service solution for performance monitoring that could be easily and seamlessly integrated into the software development lifecycle (SDLC).Use CasesThis solution will help teams track performance over a matrix of code-bases, configurations, environments, etc.Here are a few use cases we envision: Trigger performance measurement via command line interface (CLI); Trigger performance measurement on pull request (PR); Trigger performance measurement after deployment; Schedule performance measurement; Visualize performance reports; Visualize how performance trend by release or over time; Define performance budgets that could fail PRs or rollback deployments.ImpactOur test runner will empower developers and help them not only to prevent performance regressions but also to experiment and iterate faster, by squeezing every millisecond they can and ensuring their code is not a bottleneck.It can also help find hot spots and provide insight from application, to page and component levels.ArchitectureOur test solution will integrate and orchestrate multiple components to measure performance according to many scenarios: Application and mocking servers; Synthetic users; Runtime instrumentation and payload rewriting; Network link conditioning.At a very high level, system architecture:Feature list Integrates with your CI pipeline to run performance tests as you merge code in Git repo. Provides reporting in time series data which can be visualized to see the trend of your application in development phase itself. Laboratory conditions: the tests run in a very restricted environment so that we can rely on the test results without worrying about the noise that can come from network delays, CPU or memory resources. The environment are carefully monitored for any other latency or resource conflicts that may affect the performance test results. Framework Independent: If your app is a NodeJS app, our tool will seemlessly measure your performance. It does not matter if your app is React, Angular, Vue or any other framework. Local Execution : a local version can be used to run tests on your development machine before you check in code. Mock Server Integration : Tests can be run with a mock server to provide a noise-free testing. This is an optional feature. You can remove the mock server if you need to do live server testing, eg. production or stage testing. Runs for Chrome and Firefox browsers.Metrics collectedOur performance tool collects metrics from the browser API via sitespeed.io. Most of the browsers have a performance API which can be used to capture the performance measurements of an app. Sitespeed.io captures these metrics and provides a metric data which is then transformed into a readable data.Navigation API: responseTime (TTFB) backendTime frontendTime redirectionTime dnsLookUpTime serverConnection serverResponse firstPaint rumSpeedIndex domContentLoadEventStart domContentLoadEventEnd domInteractive pageLoad fullyLoadedAssets: Html content size Image content size Javascript content size Font content size CSS content size SVG content size Cookie size Total Header size Total content transfer sizeCustom metrics: (These are added by the app teams on their pages, few examples are below) aboveTheFold beforeBundle afterBundle index_start first_script entrypoint loadHTTP status codes: Number of 404 response codes Number of 200 response codesOther metrics: number of domains last modified statsPlanned features mweb support native support",
"url": "/documentation/Performance Testing/rWeb/DECLARATIVE/Introduction"
},
"documentation-performance-testing-services-declarative-introduction": {
"title": "Introduction",
"content": "SummaryOur Performance Testing solution, based on JMeter, was developed in-house and built entirely from open source components. It enables engineers to execute performance tests on their own, without any dependencies. The user is able to monitor the test in Real Time, while the test is running, and at the end of the test get the Test Report over email; and it can also be integrated with Slack, to receive the Test Report on the dedicated Slack Channel. It allows engineers to build and modify tests quickly and easily, offering considerable time savings with minimal-to-none outside help.Key Features Ability to run performance tests without performance engineering team involvement No licensing or other third party costs involved, as the tool is build in-house from open source components Estimated time-savings of 7 hours minimum of combined Performance+DevEngineer time for basic API tests For existing tests, you can modify the API’s endpoint URL, Data Files, Workload Model etc. quickly and, easily Readily observe and identify your project’s performance trends and plan accordingly The Slack integration allows you to post the test reports on the dedicated channel All Stats are in one place; easy to understand your app/api performance at a glance Ability to monitor your test in Real Time, while the test is executing All Infrastructure in on cloud provider and it is easily scalableUse CaseTesting a New or Existing APIA developer wants to track the performance of an API call, a HTTP POST Method Call used to generate a promotional coupon as part of GOP - OneWalmart. They are interested in the following performance characteristics: Response Time ThroughputReport Once the test is completed, a similar report will be generated and sent to the email provided during test executionArchitectureFeature ListPhase 1 Ability to Execute Independently through the UI One Step Ramp up Model Both HTTP and HTTPS Protocols Available HTTP Methods Available Include both GET and, POST The Ability to Send Header Information as part of the Request Adding Single Column Data Files in CSV Format UI Showing Trend Graphs UI Showing Test Status, whether the Test is Executing or, Queued Slack Integration for Reporting Email Integration for Sending Reports Integration with GIT Data Files, Workload and Use Case ModificationPhase 2 Multiple Step Ramp up Model Integration with Medusa Able to Hit Custom Port with the RequestPlanned Features Run All Use Cases Sequentially at the Project Level Text Validation on the Response Ability to Use Random Variables Ability to Use UUID Variable .perf File Validation VU’s Graph on the UI Ability to Stop the Test Adding Wait Time between Requests Enable Transactional or Workflow Model Flows Passing Values between Requests The Ability to Parse Response Data The Ability to Provide a User Specified Slack Channel",
"url": "/documentation/Performance Testing/Services/DECLARATIVE/Introduction"
},
"documentation-mocking-rweb-javascript-training-guide": {
"title": "Training Guide",
"content": "120 minMocking 101Covered topicsUnderstand of mocking solution and it's featuresHow to set up and start mock serverBasic usage of mocking solution's functionalitiesStart120 minMocking 201Covered topicsLearn creating dynamic URLsRead various REST call request informationCustomize mocked responseStart120 minMocking 301Covered topicsReturning responseSetMockId and APIs for itParallel SessionsStart120 minMocking 401Covered topicsMaintain states in mock serverMocking utility methodsSupported Rest APIs for mock serverStart",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Training Guide/"
},
"documentation-mocking-rweb-javascript-introduction": {
"title": "Introduction",
"content": "Why Use Mock Server?Most of the applications rely on one or many back end services. For successful test execution and fast development, all the dependent backend services should be reliable 100% of the time. However that is not possible as the backend services may be down from time to time for various reasons or may have data inconsistency issues which makes testing/development against live services inefficient and time consuming.To overcome above mentioned limitations, our mocking solution can be used to quickly stub the API responses that are used by your application.We provide a mocking solution which can be leveraged to quickly stub the REST API responses that are used by your application during development or testing. The application points to the mock service host address instead of the live service. Pre-recorded responses are then returned for various endpoints from the mock service. Since there is minimal logic when writing mock service, maintenance and development cost for mock service is minimal. Some of the major development pain-points addressed by the mocking solution are: Unstable services - Teams have saved upto 12 hours/week of development as well as testing time due to downtime / instability of external services. Inconsistent Data - Teams have reduced the test data setup time by about 27 hours/week by eliminating the dependency on external teams for test data setup. Test flakiness - Teams have reduced test flakiness by about 25% Test against negative or unreal scenarios - Teams have reported to have increase test coverage for negative scenarios from no tests before to upto 15 test cases now by simulating service faults deterministicallySome of the key features of the mocking solution are: Ease of setup - Very easy to setup mocked data and use it while development or testing your application Drop and Respond - Respond with a JSON file based on the url route path automatically by dropping JSON response file in folder mapping to url path Test Reuse - ability to execute test cases against mock or live serviceThe mocking solution helps the teams develop and test their web and mobile applications in local as well as CI environments.Feature list Ease of setup - Very easy to setup mocked data and use it while development or testing your application Test Reuse: Execute same test cases against mock or live service. Drop-And-Respond: Respond with a JSON file based on the url route path automatically by dropping json response file in folder mapping to url path. Test De-coupling: No coupling with test cases - Test cases are independent of mock implementation except that setting the desired response for the mock service (which has no impact if the test case is run against a live service). Respond with mocked data from a directory: Mocked data response from specific directory irrespective of Rest APIs Common Utilities: Common utility methods are provided as part of the mocking service which allows quicker test development. UI Interface: Mock service UI for manual testing/debugging. HTTPS Support: HTTPS support for all the urls. Parallel Sessions: Support for single instance mock server for parallel processes Shared Mock data: Allows fetching of mocked data and routes from multiple Git repositories Magellan/Nightwatch integration: Ability to use mocking service with Magellan tests Dynamic Transposition of Mock Data (JSON): Ability to modify response on the fly Support for all file types: Auto evaluation of response file extension and mime type Swagger integration: Automatic mock creator for web-services with swagger definition Platform independent mocks: Mock any service irrespective of the language it is written in Server states: Ability to mock server state Support for Mobile applications: Ability to mock services for mobile applications Manual tests against mock service: Ability to run tests manually against mock servicePlanned features Ability to specify various data storage for mock data Auto-refresh of data Network and Test APIs to support instrumentation Debugging tool to help development by supporting auto-replay of data Support to auto-generate endpoint URLs for mocking Support for changing mocked data via UI",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Introduction"
},
"documentation-mocking-rweb-javascript-getting-started": {
"title": "Getting Started",
"content": "Pre-Requisite Please install the latest Node.jsSetting Mock ServerTo set up mock server, you need only three things: Install mock-server module. Routes for mock-server. Script to start mock-server.Follow the steps below to set-up mock server: Create a new directory mock-server. Create a new file package.json under mock-server directory. Add Mock Server module dependency in package.json as shown below. { \"name\": \"test-midway\", \"dependencies\": { \"testarmada-midway\": \"^1.0.1\" }, \"scripts\": { \"start-mock\": \"node mocks/run-mock-server-console.js\" } } Create another directory mocks under the mock-server directory. Under the directory mocks, create a file endpoints.js with the following code - This file will contain the routes that you want to mock var midway = require('testarmada-midway'); // Required midway.id('example'); // Required // add a route that returns a message \"hello world\" midway.route({ id: 'message', label: 'hello message', path: '/message', method: 'GET', variantLabel: 'hello world', handler: function(req, reply) { reply({message: 'hello world'}); } }); Under the directory mocks, create a file run-mock-server-console.jswith the following code - This file will contain the start-up script for mock server // load mocked endpoint require('./endpoints'); var midway = require('testarmada-midway'); midway.start({ host: 'localhost', mockedDirectory: './mocks', // this can be provided as an absolute path as well. port: 8080, project: 'HelloMidway', //Replace HelloMidway with your project name (without dashes). }); Now open terminal/cmd prompt and navigate to the directory mock-server and run the following command to install Mock Server and dependencies: npm install Starting Mock Server To start mock-server use the following command and than go to http://localhost:8080/midway for mock-server admin-ui. npm run start-mock Common Use Cases Starting mock server on HTTPS port - To enable https, add httpsPort with the desired port number in server start script as shown below: midway.start({ port: 8080, httpsPort: 4444, host: 'localhost', mockedDirectory: './test/resources/mocked-data', project: 'HelloMidway' }); Mocking different REST methods - To mock different rest methods, change the method value in the midway.route() object to any one of the following desired values: POST GET PUT DELETE OPTIONS PATCH Returning different data set for the same mocked route (Variants) - Variants allows to return a different set of data for the same mocked route. To add one or more variants, attach the variant object to midway.route() as shown below: midway.route({ id: 'message', label: 'Hello message', path: '/message', method: 'GET', variantLabel: 'hello world', handler: function (req, reply) { reply({message:'Hello World'}) } }) .variant({ id: 'universe', label: 'hello universe', handler: function (req, reply) { reply({message:'hello universe'}) } }) .variant({ id: 'universe', label: 'hello galaxy', handler: function (req, reply) { reply({message:'Hello Galaxy'}) } }); To get a different set of response, go to admin-ui and select a different variant for the above route and hit http://localhost:8080/message on your favorite browser. Storing mocked response in a file - This feature allows you to respond with a static data stored in a file instead of hard coding the response data in the routes definition. // Automatic reply of the file midway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/test', method: 'GET', variantLabel: 'test-1', handler: function(req, reply) { midway.util.respondWithFile(this, reply); } }) .variant({ id: 'universe', label: 'test-2', handler: function (req, reply) { midway.util.respondWithFile(this, reply); } }); In the above setup, file needed for default route handler (test-1) should be located at (file location/name is based on mockedDirectory/route/method/[default|variant_name].{ext}) ./mocks/product/grouping/api/collection/GET/default.{ext} If this would be a POST call than the file should have been at ./mocks/product/grouping/api/collection/POST/default.{ext} The file name for variants should change from default.{ext} to universe.{ext} in above example that is the file name should be the variant name. Directing Traffic To Mock ServerTo mock live services, your application should allow to configure it to be directed to a mock service instead of live services as shown below:Please update your app server or application by changing the host name of your live service with the host name for your mock server.Mock Server Set-up Flow Identify REST endpoints that needs to be mocked. Gather mocked data for those REST endpoints. Create Mocked Routes by adding them in endpoints.js file. Start Mock Server. Start Your Application server that points to the Mock Server host name instead of live-service. Run your application and the mocked data will be returned for mocked routes.",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Getting Started"
},
"documentation-mocking-rweb-javascript-faq": {
"title": "FAQ",
"content": "What Can Be Mocked?Any Restful service API can be mocked such as: GET POST PUT DELETE OPTIONS and so on..Can AJAX Calls Be Mocked?Yes - It is same as for any other backend service. For AJAX call, point it to the mocked server instance instead of the actual back end service and add a mocked route in the file containing mocked routes for mock server.What Are The Pre-Requisites? node.js 4+ (npm is included in the package)How Can I Add Mock Server Dependency To My Node Project?\"dependencies\": { \"testarmada-midway\": \"1.0.1\" // add the latest version}How To Add A Mocked Route?Add the following code in your routes file, typically endpoints.jsmidway.route({ id: 'helloWorld', // required label: 'Hello World', // Used for Mock Server UI path: '/helloWorld', // the path you want to mock method: 'GET', // The Rest Method you want to mock for this API handler: function (req, reply) { // Add Logic to massage data before returning back to the request. reply('Hello World'); }});How To Create Dynamic URLs?By adding the URL part in curly brackets that you would liek to by dynamic such as /get/customerInfo/{customerid}/{zipcode}For example:midway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}/{zipcode}', // both customerid and zipcode will be dynamic method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { reply('How to read the customer id :('); }});How To Read Dynamic URLs In Request?var midway = require('testarmada-midway');midway.route({ path: '/get/customerInfo/{customerid}/{zipcode}' handler: function(request, reply) { var params = request.params; var customerid = params.customerid; // customerid is 123 if request is \"/get/customerInfo/123/92127\" var zipcode = params.zipcode; // zipcode is 92127 if request is \"/get/customerInfo/123/92127\" }}); How To Read Header Parameters In Request?var midway = require('testarmada-midway');midway.route({ path: '/api/getCart' handler: function(request, reply) { var headers = request.raw.req.headers; var authorization = headers.authorization; }}); How To Read Payload In Request?var midway = require('testarmada-midway');midway.route({ path: '/api/getCart' handler: function(request, reply) { var payload = request.payload; // foo would be \"bar\" if the posted body content (as JSON) is {\"foo\": \"bar\"} var foo = payload.foo; }}); How To Read Query Parameters In Request?var midway = require('testarmada-midway');midway.route({ path: '/api/getCart' handler: function(request, reply) { var queryParams = request.query; // foo would be \"bar\" if incoming request is \"/api/getCart?foo=bar\" var foo = queryParams.foo; }}); How To Set Custom Headers In Mocked Response?Preferred Waymidway.route({ id: 'header', label: 'Test Headers', path: '/api/testHeaders', handler: function (req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; midway.util.respondWithFile(this, reply, {headers: myHeaders}); }});Alternate Waymidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { reply({message: 'test'}) .header('X-Res-Header', 'I\\'m a custom response header') }});How To Set Custom Cookies In Mocked Response?Preferred Waymidway.route({ id: 'cookie', label: 'Test Cookies', path: '/api/testCookies', handler: function (req, reply) { var cookies = [ {name: 'com.wm.customer', value: 'vz7.0b5c56'}, {name: 'CID', value: 'SmockedCID', options: {domain: 'domain', path: '/'}}, {name: 'anotherCookie', value: 'cookieValue'} ]; midway.util.respondWithFile(this, reply, {cookies: cookies}); }});Alternate Waymidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { reply({message: 'test'}) .state('test-cookie', 'I\\'m a custom response cookie') }}); How To Set CORS Headers?var corsHeaders = { origin: ['*'], headers: [\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept\"], credentials: true,}// Itemsmidway.route({ id: 'tempo', label: 'Tempo', path: '/tempo1', config: { cors: corsHeaders }, handler: function(req, reply) { midway.util.respondWithFile(this, reply); }});What Is respondWithFile Utility?This feature allows you to respond with a data stored in a file instead of hard coding the response data in the routes definition. This way user does not have to hard-code/change the response in handler and rather can just swap the file with different data without even bringing the server down. midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); } });In the above example, mock server will automatically look for a file default.{some_extension} at ./mocked-data/get/fromFile/GET/default.{some_extension}How File Path Is Calculated For respondWithFile Utility?The path to the mocked data file is auto-calculated based on the route path. For example if the route path is /get/cart than for the default variant, mock server will look for the default.{some_extension} file at ./mocked-data/get/fromFile/GET/default.{some_extension}. For variants, the name of the file should be changed from default to the variant name as shown below:midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }}).variant({ id: 'textData', label: 'Text Data', handler: function (req, reply) { midway.util.respondWithFile(this, reply); }});In above example mock server will look for ./resources/mocked-data/get/fromFile/GET/textData.{some_extension} file for the variant textDataCan I Provide A Custom File Location respondWithFile Utility?Yes. By adding filePath parameter as shown in below example:midway.route({ id: 'CustomResponseFile', label: 'Response From Custom Path', path: '/get/customFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {filePath: './custom.json'}); }});In above example mock server will look for the file under MockedDirectory only but at ./mocked-data/custom.jsonHow To Respond Only With Code?midway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { reply().code(400); }});Can I Return A Response Code With respondWithFile Utility?Yes - by adding code parameter as shown in below example:midway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400}); }});What Is MockedDirectory Path?Mocked directory path is the location to the base directory where all your mocked response file will be stored. This parameter is defined in run-mock-server-console.js file. It is defined at the start of mock server as shown in the code below:require('./endpoints');require('testarmada-midway').start({ host: \"localhost\", mockedDirectory: \"./resources/mocked-data\", port: 8000, project: 'HelloMidway'});Location For Response File For RespondWithFile?If you have set your default folder to be mocked-data, then based on your URL path:For default variant, mock server will look for ./mocked-data/product/grouping/api/collection/GET/default.json and for mixItem variant mock server will look for ./mocked-data/product/grouping/api/collection/GET/mixItem.jsonWhat Are Variants?Variants allows to return a different data set for a given mocked route. Variants can be selected either in the admin UI or through automation APIs to determine what type of response a route should have. Routes are defined using the variant method on the Route object (returned by calling the route method). An object parameter is provided with the following attributes id: the variant id - used for the RESTful admin API and profile settings label: (optional) the variant label - used for display on the admin panel handler: (optional) the HAPI route handler which provides the route responseVariants are useful because they allow you to test multiple scenarios that can happen with your route. Say, for example, you have a route exposing the ability to update a password. You might have several exceptional scenarios that you would want to test out (each could be a variant that you simply select to tell the route handler to use the appropriate response) the password was reset successfully the password didn’t pass validation the old password wasn’t entered correctly the username doesn’t exist and so on…How To Add A Variant To A Route?To add a one or more variants do the following:midway.route({ id: 'message', label: 'Message', path: '/get/message', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { reply('Hello'); }}) .variant({ id: 'hello', label: 'Hello World', handler: function (req, reply) { reply('Hello World'); } }).variant({ id: 'hello', label: 'Hello Universe', handler: function (req, reply) { reply('Hello Universe'); } }); How To Switch Variants In Test Case?browser.setMockVariant({ fixture: \"fixture id\", variant: \"variant id\" }); How To Switch Variants With HTTP Call?You can also switch the variants via HTTP call (Recommended only when not using Midway as a library). As an example, if you want to set variant to helloUniverse for the route below: midway.route({ id: 'helloWorld', label: 'Hello World', path: '/helloWorld', method: 'GET', handler: function (req, reply) { reply('Hello World'); } }) .variant({ id: 'helloUniverse', label: 'Hello Universe', handler: function (req, reply) { reply('Hello Universe'); } });curl -H \"Content-type: application/json\" -X POST -d '{\"variant\":\"<variant>\"}' <host>:<port>/midway/api/route/<routeId>So for the above route, you can switch the variant to helloUniverse like this:curl -H \"Content-type: application/json\" -X POST -d '{\"variant\":\"helloUniverse\"}' http://localhost:8000/midway/api/route/helloWorldWhen using parallel sessions, if you want to switch a variant for a route for a particular session, register the session with mock server like this:curl <host>:<port>/midway/api/registerSession// e.g curl http://localhost:8000/midway/api/registerSessionIf sessions are available, mock server will return a response like: {\"session\":\"33b08d\"}Extract the session id from response and append it to the route id you want to switch variant for e.g:curl -H \"Content-type: application/json\" -X POST -d \"variant\":\"helloUniverse\"}' http://localhost:8000/midway/api/route/helloWorld-33b08dWhat Is Mock Server UI Used For?UI can be used to view and test mocked routes as well as for manual switching of variants when running tests manually.What Is Parallel Sessions?Parallel sessions allows you to run multiple instance of server virtually while running only one server. This is helpful when you are running multiple test cases which access the same routes but different variants as parallel sessions allow you to set different variants on same routes without conflicting. This saves CPU and RAM both as only one server is running instead of multiple. Please see the call flow explaination without and with Parallel Sessions Below:Call Flow Without Parallel SessionsCall Flow With Parallel SessionsHow Can I Enable Parallel Sessions On Mock Server?Add sessions parameter with number of virtual services you want as shown in below example while startung mock Server.require('./endpoints');var midway = require('testarmada-midway');midway.start({ host: \"localhost\", mockedDirectory: \"./resources/mocked-data\", port: 8000, sessions: 2, project: 'HelloMidway'});How Can I Register a Session For Parallel Sessions?var sessionId = midway.registerSession();How Can I Close A Session For Parallel Sessions?var closeSession = midway.closeSession(sessionId);Does Mock Server Has Any Utility To Modify JSON Data Stored In Files?Yes - Mock Server exposes transpose option that cna be passed in respondWithFile method to modify the JSON files dynamically.How Does transposeData Work To Modify JSON Data Stored In Files?If you have many variants for a Rest end point and the mocked data for all variants can use the same JSON response with few changes to the values, than this feature is what you need. This feature allows you to dynamically change a JSON file before sending the response back from the mock server for the request. It removes the need of having one to one mapping of static JSON files with each variants.// Static Response JSON File{ id: \"1234\", name: \"toothpaste\" details: [ { flavor: \"Mint 1\", Size: \"10\", Size_Type: ounce }, { flavor: \"Mint\", Size: \"10\", Size_Type: ounce } ]}// Sample code for substituting id from 1234 to 7777 and flavor from Mint to Mint 2 for second array element in routesmidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { var dataToChange = { 'id': '7777', 'details[1].flavor': 'Mint 2' } midway.util.respondWithFile(this, reply, {transpose: dataToChange}); }});// Dynamic Response JSON File returned from Mock service{ id: \"7777\", name: \"toothpaste\" details: [ { flavor: \"Mint 1\", Size: \"10\", Size_Type: ounce }, { flavor: \"Mint 2\", Size: \"10\", Size_Type: ounce } ]}Can I Use transposeData Functionality Outside Of respondWithFile?Yes - You can use it by Midway Utils.var fileLocation = require(\"path\").join(__dirname, './resources/test-data/data-transposition-test.json');var dataSet = utils.readJsonFile(fileLocation);var dataToChange = { 'items.item[0].id': 1234, // substitue id 0001 to 1234 'items.item[0].val': \"value\", // Add 'val' to first array element of items.item 'items.item[1].id': 4567, // Add 'id' to second array element of items.item 'items.item[0].batters.batter[0].id': 5678 // substitue id 1001 to 5678}substitutedData = midway.util.transposeData(dataSet, dataToChange);// Base JSON file - data-transposition-test.json{ \"items\": { \"item\": [ { \"id\": \"0001\", \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"batters\": { \"type\" : 1, \"batter\": [ { \"id\": \"1001\", \"type\": \"Regular\" }, ] }, \"topping\": [ { \"id\": \"5001\", \"type\": \"None\" } ] } ] }};// Resulted JSON{ \"items\": { \"item\": [ { \"id\": 1234, \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"val\": \"value\" \"batters\": { \"type\": 1, \"batter\": [ {\"id\": 5678, \"type\": \"Regular\"} ] }, \"topping\": [ {\"id\": \"5001\", \"type\": \"None\"} ] }, { \"id\": 4567 } ] }};Why Mock Server Returns Error 415 Unsupported Media Type?If you’re using content type like application/graphql, follow this example midway.route({ id: 'id', label: 'id', path: '/graphql', method: ['POST', 'PUT'], config : { payload: { parse: false, allow: 'application/graphql' } }, handler: function (req, reply) { midway.util.respondWithFile(this, reply, {code: 200}); } });For more details, read this",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/FAQ"
},
"documentation-mocking-rweb-javascript-contribution-guide": {
"title": "Contribution Guide",
"content": "ArchitectureThese are the very high level components of mocking eco-system.The below diagram shows the mocking components in detail.The mocking service uses midway-smocks which provides the stateful HTTP mocking service built on top of HAPI. It allows to add routes and different scenarios for each route.In addition, the mocking service provides certain utilities via midway-util. It also provides logging facility with midway-loggerMock Server Start flowThe mocking service exposes its features via API’s and HTTP end points. Lets take a look at the sequence of events when the mock server is started.In the above diagram, the actor can be the test code which starts mock server or a developer using the mock service for local development / testing. Users can specify what routes to mock by specifying them in endpoints.js Midway’s start() is invoked with options to start the Midway server Midway creates an instance of Hapi server Midway adds the routes for the system API’s it supports Midway gets the plugin from midway-smocks Midway registers the plugin it obtained from the above step Midway starts the server Once the Midway server is started, you can use the Midway API’s via HTTP Calls or libraries [Read API Guide for examples] Parallel vs non-parallel sessionsWithout Parallel sessionsIf we want to run two test cases in parallel, mocking the same route and returning different data, it won’t be possible with running one mock server and sharing across the whole test suite. So we needed to run one mock server and one application server per test case.With Parallel sessionsWith parallel sessions, we can share one application server and mock server for the whole test suite. It allows to mock the same route but different data for different test cases.To use parallel sessions, the mock server is started with pre-defined number of sessions. For each test, the test case needs to register a session with the mock server. The mock server returns a unique session id which is then sent as part of the request to the application server. If the request gets routed to the mock server for a mocked route, the request handler in mock server extracts the session id from the request, and prepends it to the route. For e.g, if the session id is “123”, it is prepended to the route “/api/getCart” and the route becomes “/123/api/getCart”. For another test using session id “456” , the route will become “/456/api/getCart”. This enables the mock server to be able to return two different responses for the same mocked route.Tech stackLanguage : NodejsNode Version: 4+Unit Tests: MochaCode formatting: EslintCode Coverage Report: IstanbulDeployment informationMocking components are released as npm librariesGit repository informationThe source code for all mocking components reside in Github. Midway Midway Util Midway Magellan Nightwatch Midway Logger Midway Smocks Midway SwaggerDevelopment processTo contribute to the mocking fleet, please follow these steps: Fork the repository https://github.com/TestArmada/midway. If your Github username is “abc” for e.g, your forked repository will be https://github.com/abc/midway. Clone this forked repository using git clone https://github.com/<username>/midway.git and make “midway” your working directory. Create a branch on local with git checkout -b <your branch name>. Note The default branch for all projects is development so any branch you create will be off the development branch. Install dependencies using npm install. Make the code changes in the branch you created in step (3) and write / update the unit tests to verify your changes. Run unit tests using npm test. We use eslint to ensure code formatting. This step runs both unit tests as well as verifies code formatting. We use istanbul for code coverage reporting. 95% is the minimum code coverage we expect for all our components. Once you’re ready, submit your pull request from your branch against the development branch of Midway (https://github.com/TestArmada/midway/tree/development). The PR triggers a Travis build which runs the tests in CI environment (same steps as in (5) above). Once the PR is reviewed, a team member merges the PR into the development branch. When the development branch is merged to master, a team member will push a tag to master, a Travis build is triggered and publishes a new version of the package to npm registry. Note: The same steps above are applicable for contributing to any of the mocking components.",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/Contribution Guide"
},
"documentation-mocking-rweb-javascript-api-guide": {
"title": "API Guide",
"content": " Mocking API’s Start Mock Server - start() Stop Mock Server - stop() Create Mocked Route - route() Create Variant - variant() Set variant - setMockVariant() Add global variants - addGlobalVariant() Respond With File - respondWithFile() Respond with mock variant - respondWithMockVariant() Set Mock Id - setMockId() Get Mock Id - getMockId() Reset Mock Id - resetMockId() Reset url count - resetURLCount() Get url count - getURLCount() Register session - registerSession() Close session - closeSession() Check session - checkSession() Get sessions - getSessions() Clear sessions - clearSessions() Get project name - getProjectName() Get port information - getPortInfo() Add state - addState() Get state - getState() Clear state - clearState() Enable Metrics - enableMetrics() Check if metrics are enabled - isMetricsEnabled() Dynamic transposition of JSON data - transposeData() Kill process - killProcess() Read contents of a file - readFile() Read contents of a file - readFileSynchronously() Read contents of JSON file - readJsonFile() Write to file - writeFile() Delete file - deleteFile() Check if directory exists - checkDirectoryExists() Check if file exists - checkFileExists() Set Log level - setLogLevel() Get Log level - getLogLevel() Reset Log level - resetLogLevel() Mocking API’sStart Mock Server - start()This API allows to start the mock server.midway.start(options, callback);The following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below No callback The first argument to callback function is the server instance if the start is successful, else it is an error. No where options has the following attributes: Attribute Description Required host Hostname for mock server (default: localhost) No port Port for mock server (default: 8080) No httpsPort Https port for mock server No mockedDirectory Path to the mocked data directory (default: resources/mocked-data w.r.t working directory). No sessions Number of parallel sessions to start the mock server with (default: 0) No collectMetrics Enable mock server to collect usage metrics (default: true) No project Name for your project (default: default) No Examplevar midway = require('testarmada-midway');midway.start({ host: 'localhost', port: 12000, httpsPort: 12001, mockedDirectory: '/resources/mockedData', sessions: 3, project: 'My Project'});Stop Mock Server - stop()This API allows to stop the mock server.midway.stop(server, callback);The following attributes are supported: Attribute Description Required server server instance returned by start() method Yes callback The first argument to callback function is an error if an error is encountered in stopping the server, null otherwise No Examplevar midway = require('testarmada-midway');var server = midway.start(options, callback);// do something with mock servermidway.stop(server, function (error) { if (error) { console.log('Unable to stop mock server'); } else { console.log('Mock Server stopped'); }});Create Mocked Route - route()This API allows to create/add required mocked REST endpoints.midway.route(options);The following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below Yes where options has the following attributes: Attribute Description Required id The unique route id for the mock server Yes label The route label used for display on the Midway Admin Panel No path The route path Yes method The HTTP route method (defaults to GET) No handler The HAPI route handler which provides the route response. This is optional because you could use multiple variants to handle the response (See Variants) No Examplevar midway = require('testarmada-midway');midway.route({ id: 'my_route', label: 'My Route', path: '/api/foo', method: 'GET', handler: function(request, reply) { // Add logic for handler reply('Hello'); }});Create Variant - variant()This API allows to create/add variants. Variants are route handlers that you can select manually (via Midway Admin panel) or Rest call or through Node API to select a different dataset for the response for a given route. Variants are defined using the variant() method on the Route object (returned by calling the route method).midway.route(routeOptions).variant(options)The following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below Yes where options has the following attributes: Attribute Description Required id The unique variant id for a given route Yes label The route label used for display on the Admin Panel No handler The HAPI route handler which provides the variant response for the route No Examplevar midway = require('testarmada-midway');midway.route({ id: 'my_route', path: '/api/foo', handler: function(request, reply) { // this is essentially the same as the \"default\" variant reply({firstName: 'John'}); }}).variant({ id: 'Billy', handler: function(request, reply) { reply({firstName: 'Billy'}); }}).variant({ id: 'Clark', handler: function(request, reply) { reply({firstName: 'Billy'}); }});Set variant - setMockVariant()setMockVariant can be used to set a variant to an existing API path.midway.setMockVariant(options, callback) // with Midway libraryor browser.setMockVariant(options, callback) // when using MagellanThe following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below No callback callback function to be called after setMockVariant() Yes where options has the following attributes: Attribute Description Required fixture Id defined in route Yes variant The variant defined in endpoint.js for the fixture you entered Yes portNumber Port number where the mock server is running on No midwaySessionId Midway session id, if using parallel sessions No ExampleIf the routes are defined likevar midway = require('testarmada-midway');midway.route({ id: 'hello', path: '/helloWorld', handler: function(request, reply) { reply('Hello World'); }}).variant({ id: 'universe', handler: function(request, reply) { reply('Hello Universe'); }});For the route and variant defined as above, you can set the variant to universe as follows:// when using Midway librarymidway.setMockVariant({ fixture: 'hello', // same as id in the .route() options variant: 'universe' // same as id in the .variant() options}, function (err) { if (err) { console.log('Error in setting variant:' + err); } else { console.log('Successfully set variant'); }});or // When using Magellanbrowser.setMockVariant({ fixture: \"hello\", variant: \"universe\" });or Alternately, you can also use `curl` call to set a variant with this POST call to `{host}:{port}/midway/api/route/{routeId}`curl -H \"Content-Type: application/json\" -X POST -d '{\"variant\":\"{universe}\"}' http://localhost:8080/midway/api/route/hello?returnConfig=trueYou can confirm if this works by going to Admin panel and see that for helloWorld route, the variant universe will be highlighted. Also, hitting this url http://localhost:8080/helloWorld will reply with Hello Universe.If the variant does not exist on the route, mock server returns with an Internal Server error (HTTP 500).Add global variants - addGlobalVariant()You can also add global variants that will affect all routes. The attributes to the options are same as that of variant().midway.route(routeOptions).addGlobalVariant(options)whereoptions - JSON object with the same attributes as of variant described in this sectionExamplevar midway = require('testarmada-midway');midway.addGlobalVariant({ id: '500', label: '500 error', handler: function(request, reply) { reply({ statusCode: 500, error: 'Internal Server Error' }).code(500); }})Respond With File - respondWithFile()This API allows to respond with static data stored in a file instead of hard coding the response data in the routes definition. Based on the path of the URL that is being mocked, the response file can be dropped in the directory location and the file will be automatically used by Midway for sending the response. It also allows to specify the absolute path of the response files.midway.util.respondWithFile(route, reply, options);The following attributes are supported: Attribute Description Required route Handle to the midway route object Yes reply Handle to the reply object Yes options JSON object with additional options described below No Attribute Description Required code HTTP Status code to reply with No filePath Static file path of the mocked data No delay Delay response time by this value (in milliseconds) No To use this feature, you can call respondWithFile() from inside route configuration as follows:Examplevar midway = require('testarmada-midway');// Automatic reply of the filemidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}' handler: function(req, reply) { midway.util.respondWithFile(this, reply); }}).variant({ id: 'mixItem', label: 'Mix Item' handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 204, filePath: '../mocked-data/fileName.json', delay: 1000}); }})Note the Use of midway.util to access the method respondWithFileRespond with mock variant - respondWithMockVariant()This API allows to respond with a variant on the main route handler. The ‘variant’ passed in MUST be the variant on existing route.midway.util.respondWithMockVariant(route, variant, req, reply)The following attributes are supported: Attribute Description Required route The route object Yes variant Variant on the route Yes request Request object Yes reply Reply object Yes Examplevar midway = require('testarmada-midway');midway.route({ id: 'respondWithVariant', label: 'Respond With Variant', path: '/respondWithVariant', variantLabel: 'Respond With Main Route', handler: function(req, reply) { midway.util.respondWithMockVariant(this, 'variant', req, reply); // make sure that the variant exist in the same route. }}).variant({ id: 'variant', label: 'Respond With Variant Route', handler: function(req, reply) { reply({ 'message': 'I am an example of respond_with_mock_variant instead of response of main route ' }); }});Note the Use of midway.util to access the method respondWithMockVariantSet Mock Id - setMockId()This API allows to set mock id for a given test case. If this is set, it overrides all the variants and mocked URLs responses to return mocked data from the given directory as mock-id, where mock-id is the directory name.midway.setMockId(mockId, midwaySessionId) // with Midway libraryor browser.setMockId(mocKId, midwaySessionId, callback); // when using MagellanThe following attributes are supported: Attribute Description Required mockId Mock id which is the directory name you want to respond data from Yes midwaySessionId Midway session id, if using parallel sessions No callback callback function to be invoked after mock id is set (only when using Magellan) No The file name should be in the format url-methodName-urlCount.extension for the responses stored under file. For example, for the given route belowvar midway = require('testarmada-midway');midway.route({ id: 'my_route', label: 'My Route', path: '/api/foo', method: 'GET', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }});the file name should be api-foo-GET-1.json for the first time the URL is hit. For second time the URL is hit, the file name returned would be api-foo-GET-2.json. If the specific file for the count is not present, Midway will look for default file api-foo-GET.json, which is also helpful if you want to always return the same response irrespective of the number of times the URL is hit.Example:var midway = require('testarmada-midway');midway.setMockId('cart', 'abcdef'); // All responses should be under \"cart\" directory under your mocked data directoryor browser.setMockId('cart', 'abcdef' , callback);orcurl http://localhost:8000/midway/api/setMockId/cart/abcdefTIP! For a dynamic url such as /app/{cartid}/getStatus the default file name should be app-cartid-getStatus-GET.json and the count specific file name should be like app-cartid-getStatus-GET-1.json.Get Mock Id - getMockId()This API is used to retrieve the currently set mock id.midway.getMockId(midwaySessionId);The following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No Example:var midway = require('testarmada-midway');var mockId = midway.getMockId('abcdef');or curl http://localhost:8000/midway/api/getMockId/cart/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Reset Mock Id - resetMockId()This API is used to reset currently set mock id.midway.resetMockId(midwaySessionId) // with Midway libraryor browser.resetMockId(midwaySessionId, callback); // when using MagellanThe following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No callback callback function to be invoked after mock id is set (only when using Magellan) No Example:var midway = require('testarmada-midway');midway.resetMockId('abcdef');or browser.resetMockId('abcdef', callback);or curl http://localhost:8000/midway/api/resetMockId/cart/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Reset url count - resetURLCount()This API is used to reset URL count to zero. This works in conjunction with setMockId function where you want to restart over for the URL count.midway.resetURLCount(midwaySessionId)or browser.resetURLCount(midwaySessionId, callback)The following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No callback callback function to be be invoked after the mock id is reset No Example:var midway = require('testarmada-midway');midway.resetURLCount('abcdef');or browser.resetCount('abcdef', callback); // 'abcdef' is a midway session id in use for the testorcurl http://localhost:8000/midway/api/resetURLCount/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Get url count - getURLCount()This API is used in conjunction with setMockId function where you want to get the URL count for all mocked calls.midway.getURLCount(midwaySessionId)The following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No Example:var midway = require('testarmada-midway');midway.getURLCount('abcdef');or curl http://localhost:8000/midway/api/getURLCount/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Register session - registerSession()This API is used to register a session with Midway for a test case when using parallel sessions. Midway needs to be started with sessions.midway.registerSession(); // with Midway libraryor browser.registerSession(callback); // with browser testsThe following attributes are supported: Attribute Description Required callback callback function to be be invoked after the session is registered. First argument to the callback is an error object, in case of error, null otherwise. The second argument is the registered session id (Only for browser tests) Yes You can use registerSession() to register a session with Midway and can subsequently use that session id for the current test. Midway returns a unique identifier when registering a session.If no session is available to use, Midway returns with the message NOT_AVAILABLE.ExampleIf midway server is started with sessions, for e.g 3 sessions as shown below,var midway = require('testarmada-midway');midway.start({ host: 'localhost', port: 8080, mockedDirectory: 'resources/mockedData', sessions: 3});var midwaySessionId = midway.registerSession();or browser.registerSession(function (err, sessId) { if (err) { return callback(new Error(\"Unable to get the sessionId\")); } self.midwaySessionId = sessId; client.midwaySessionId = sessId; return callback();});orcurl http://localhost:8000/midway/api/registerSessionClose session - closeSession()This API is used to close a session after running a test so it can be made available for subsequent tests.midway.closeSession(midwaySessionId);or browser.closeSession(midwaySessionId, callback);The following attributes are supported: Attribute Description Required midwaySesssionId Midway session id to be closed Yes callback callback function to be be invoked after the session is registered. First argument to the callback is an error object, in case of error, null otherwise (Only when using browser tests) Yes Examplevar midway = require('testarmada-midway');midway.closeSession('abcdef'); // abcdef is a previously registered session with Midwayor client.closeSession('abcdef', function (err) { if (err) { console.error(\"Error in closing session:\"); }});orcurl http://localhost:8000/midway/api/closeSession/abcdefNote that abcdef is a previously registered session with Midway.Check session - checkSession()This API is used to check status of a session id. It returns one of these states AVAILABLE - If the session is available for use IN_USE - If the session is in use DOES_NOT_EXISTS - If the session id passed is invalid or does not existThe following attributes are supported: Attribute Description Required midwaySessionId Midway session id Yes Examplevar midway = require('testarmada-midway');var status = midway.checkSession('abcdef');or curl http://localhost:8000/midway/api/checkSession/abcdefGet sessions - getSessions()This API is used to get sessions informationmidway.getSessions();Examplevar midway = require('testarmada-midway');var status = midway.getSessions();or curl http://localhost:8000/midway/api/getSessionsClear sessions - clearSessions()This API is used to clear the sessions information.midway.clearSessions();Examplevar midway = require('testarmada-midway');var status = midway.clearSessions();Get project name - getProjectName()This API is used to get the project name passed in Midway optionsmidway.getProjectName();Examplevar midway = require('testarmada-midway');var projectName = midway.getProjectName();Get port information - getPortInfo()This API is used to get the port information passed in Midway optionsmidway.getPortInfo();Examplevar midway = require('testarmada-midway');var portInfo = midway.getPortInfo();Add state - addState()This API is used to add a value to the server state.midway.addState(route, key, value);The following attributes are supported: Attribute Description Required route Route object Yes key Key for the state variable Yes value Value of the state variable Yes Examplevar midway = require('testarmada-midway');midway.route({ id: 'setState', label: 'Add State', path: '/login', handler: function (req, reply) { midway.addState(this, 'loggedIn', true); reply().code(204); }});Get state - getState()This API is used to read a value from the server state.midway.getState(route, key);The following attributes are supported: Attribute Description Required route Route object Yes key Key for the state variable Yes Examplevar midway = require('testarmada-midway');midway.route({ id: 'getState', label: 'Get State', path: '/isLogin', handler: function (req, reply) { var isLoggedIn = midway.getState(this, 'login'); reply(isLoggedIn); }});Clear state - clearState()This API is used to clear a state for a given session id (Defaults to default session).midway.clearState(midwaySessionId);The following attributes are supported: Attribute Description Required midwaySessionId Midway session id No Examplevar midway = require('testarmada-midway');midway.clearState(); // Clears state for default sessionmidway.clearState('abcdef') // Clears state for session id `abcdef`Enable Metrics - enableMetrics()This API is used to enable gathering of usage metrics.midway.enableMetrics(boolean);The following attributes are supported: Attribute Description Required boolean true to enable, false to disable No Examplevar midway = require('testarmada-midway');midway.enableMetrics(true); // Enables gathering of usage metricsmidway.enableMetrics(false); // Disables gathering of usage metricsCheck if metrics are enabled - isMetricsEnabled()This API is used to check if metrics gathering is enabled on Midway. Returns true if metrics gathering is enabled, false otherwisemidway.isMetricsEnabled();Examplevar midway = require('testarmada-midway');midway.isMetricsEnabled();Dynamic transposition of JSON data - transposeData()This API allows to dynamically transpose the JSON datamidway.util.transposeData(dataSet, dataToChange);The following attributes are supported: Attribute Description Required dataSet The data set which needs to change Yes dataToChange The changes needed in the data set Yes To change the JSON data on fly (edit existing values or add values).// Base JSON file{ \"items\": { \"item\": [ { \"id\": \"0001\", \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"batters\": { \"type\" : 1, \"batter\": [ { \"id\": \"1001\", \"type\": \"Regular\" }, ] }, \"topping\": [ { \"id\": \"5001\", \"type\": \"None\" } ] } ] }}// Code examplevar dataToChange = { 'items.item[0].id': 1234, // substitue id 0001 to 1234 'items.item[0].val': \"value\", // Add 'val' to first array element of items.item 'items.item[1].id': 4567, // Add 'id' to second array element of items.item 'items.item[0].batters.batter[0].id': 5678 // substitue id 1001 to 5678}// when using utils classvar fileLocation = require(\"path\").join(__dirname, './resources/test-data/data-transposition-test.json');var dataSet = utils.readJsonFile(fileLocation);substitutedData = midway.util.transposeData(dataSet, dataToChange);// When using with respondwithFile (This will read the file based on url path and transpose the data)midway.util.respondWithFile(this, reply, {transpose: dataToChange});// Resulted JSON{ \"items\": { \"item\": [ { \"id\": 1234, \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"val\": \"value\" \"batters\": { \"type\": 1, \"batter\": [ {\"id\": 5678, \"type\": \"Regular\"} ] }, \"topping\": [ {\"id\": \"5001\", \"type\": \"None\"} ] }, { \"id\": 4567 } ] }}Note the Use of midway.util to access the method transposeDataKill process - killProcess()This API allows to Kill a process with a pidmidway.util.killProcess(pid, signal, callback);The following attributes are supported: Attribute Description Required pid process id to kill Yes signal Signal to send (defaults to SIGKILL if passed undefined) Yes callback Callback function after killprocess completes No Examplevar midway = require('testarmada-midway');midway.util.killProcess(18222, 'SIGKILL', function () { console.log('Process killed);});Note the Use of midway.util to access the method killProcessRead contents of a file - readFile()This API allows to read contents of a file asynchronouslymidway.util.readFile(filePath, callback);The following attributes are supported: Attribute Description Required file path Absolute or relative location of file Yes callback Callback function after file is read. If file is read successfully, the second argument is the file data. In case of error, the first argument is an error. Returns promise if callback is omitted No Examplevar midway = require('testarmada-midway');midway.util.readFile('data.json', function (err, fileData) { if (err) { console.log('Error in reading file ', err); } else { console.log(fileData); }});Note the Use of midway.util to access the method readFileRead contents of a file - readFileSynchronously()This API allows to read contents of a file synchronouslymidway.util.readFileSynchronously(filePath);The following attributes are supported: Attribute Description Required file path Absolute or relative location of file Yes Examplevar midway = require('testarmada-midway');midway.util.readFileSynchronously('data.json');Note the Use of midway.util to access the method readFileSynchronouslyRead contents of JSON file - readJsonFile()This API allows to read contents of a JSON file synchronouslymidway.util.readJsonFile(filePath);The following attributes are supported: Attribute Description Required file path Absolute or relative location of JSON file Yes Examplevar midway = require('testarmada-midway');midway.util.readJsonFile('data.json');Note the Use of midway.util to access the method readJsonFileWrite to file - writeFile()This API allows to write file contents to a filemidway.util.writeFile(filePath, file data, callback);The following attributes are supported: Attribute Description Required file path Absolute or relative location of file Yes file data contents to write Yes callback Callback function after writeFile completes Yes Examplevar midway = require('testarmada-midway');midway.util.writeFile('hello.txt', 'hello world blah blah', function () { console.log('Wrote to file successfully');});Note the Use of midway.util to access the method writeFileDelete file - deleteFile()This API allows to write file contents to a filemidway.util.deleteFile(filePath, callback);The following attributes are supported: Attribute Description Required file location Absolute or relative location of file to delete Yes callback Callback function after deleteFile completes Yes Examplevar midway = require('testarmada-midway');midway.util.deleteFile('filetoDelete.txt', function (err) { if (err) { console.log('Error in deleting file'); }});Note the Use of midway.util to access the method deleteFileCheck if directory exists - checkDirectoryExists()This API allows to check if a directory exists. Returns true if directory exists, false otherwise.midway.util.checkDirectoryExists(directoryPath);The following attributes are supported: Attribute Description Required directory path Location of directory to check Yes Examplevar midway = require('testarmada-midway');midway.util.checkDirectoryExists('/home/data');Note the Use of midway.util to access the method checkDirectoryExistsCheck if file exists - checkFileExists()This API allows to check if a file exists. Returns true if file exists, false otherwise.midway.util.checkFileExists(filePath);The following attributes are supported: Attribute Description Required file path Location of file to check Yes Examplevar midway = require('testarmada-midway');midway.util.checkFileExists('/home/data');Note the Use of midway.util to access the method checkFileExistsSet Log level - setLogLevel()This API allows to set log level on Midwaymidway.log.setLogLevel(logLevel); // when using MidwayorLogger.setLogLevel(logLevel); // when using Midway-LoggerThe following attributes are supported: Attribute Description Required logLevel Log level you want to set .Valid values (warn/info/debug/error) Yes Examplevar midway = require('testarmada-midway');midway.log.setLogLevel('debug');orcurl -X GET http://localhost:8080/midway/api/setloglevel/debugGet Log level - getLogLevel()This API allows to get the current log level on Midwaymidway.log.getLogLevel(); // when using Midwayor Logger.getLogLevel(); // when using Midway-LoggerExamplevar midway = require('testarmada-midway');midway.log.getLogLevel();orvar Logger = require('testarmada-midway'-logger');Logger.getLogLevel();orcurl -X GET http://localhost:8080/midway/api/getloglevelReset Log level - resetLogLevel()This API allows to reset the log level of Midway to info (Default log level)midway.log.resetLogLevel();or Logger.resetLogLevel();Examplevar midway = require('testarmada-midway');midway.log.resetLogLevel();orvar Logger = require('testarmada-midway'-logger');Logger.resetLogLevel();or curl -X GET http://localhost:8080/midway/api/resetloglevel",
"url": "/documentation/Mocking/rWeb/JAVASCRIPT/API Guide"
},
"documentation-mocking-services-javascript-training-guide": {
"title": "Training Guide",
"content": "120 minMocking 101Covered topicsUnderstand of mocking solution and it's featuresHow to set up and start mock serverBasic usage of mocking solution's functionalitiesStart120 minMocking 201Covered topicsLearn creating dynamic URLsRead various REST call request informationCustomize mocked responseStart120 minMocking 301Covered topicsReturning responseSetMockId and APIs for itParallel SessionsStart120 minMocking 401Covered topicsMaintain states in mock serverMocking utility methodsSupported Rest APIs for mock serverStart",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Training Guide/"
},
"documentation-mocking-services-javascript-introduction": {
"title": "Introduction",
"content": "Why Use Mock Server?Most of the applications rely on one or many back end services. For successful test execution and fast development, all the dependent backend services should be reliable 100% of the time. However that is not possible as the backend services may be down from time to time for various reasons or may have data inconsistency issues which makes testing/development against live services inefficient and time consuming.To overcome above mentioned limitations, our mocking solution can be used to quickly stub the API responses that are used by your application.We provide a mocking solution which can be leveraged to quickly stub the REST API responses that are used by your application during development or testing. The application points to the mock service host address instead of the live service. Pre-recorded responses are then returned for various endpoints from the mock service. Since there is minimal logic when writing mock service, maintenance and development cost for mock service is minimal. Some of the major development pain-points addressed by the mocking solution are: Unstable services - Teams have saved upto 12 hours/week of development as well as testing time due to downtime / instability of external services. Inconsistent Data - Teams have reduced the test data setup time by about 27 hours/week by eliminating the dependency on external teams for test data setup. Test flakiness - Teams have reduced test flakiness by about 25% Test against negative or unreal scenarios - Teams have reported to have increase test coverage for negative scenarios from no tests before to upto 15 test cases now by simulating service faults deterministicallySome of the key features of the mocking solution are: Ease of setup - Very easy to setup mocked data and use it while development or testing your application Drop and Respond - Respond with a JSON file based on the url route path automatically by dropping JSON response file in folder mapping to url path Test Reuse - ability to execute test cases against mock or live serviceThe mocking solution helps the teams develop and test their web and mobile applications in local as well as CI environments.Feature list Ease of setup - Very easy to setup mocked data and use it while development or testing your application Test Reuse: Execute same test cases against mock or live service. Drop-And-Respond: Respond with a JSON file based on the url route path automatically by dropping json response file in folder mapping to url path. Test De-coupling: No coupling with test cases - Test cases are independent of mock implementation except that setting the desired response for the mock service (which has no impact if the test case is run against a live service). Respond with mocked data from a directory: Mocked data response from specific directory irrespective of Rest APIs Common Utilities: Common utility methods are provided as part of the mocking service which allows quicker test development. UI Interface: Mock service UI for manual testing/debugging. HTTPS Support: HTTPS support for all the urls. Parallel Sessions: Support for single instance mock server for parallel processes Shared Mock data: Allows fetching of mocked data and routes from multiple Git repositories Magellan/Nightwatch integration: Ability to use mocking service with Magellan tests Dynamic Transposition of Mock Data (JSON): Ability to modify response on the fly Support for all file types: Auto evaluation of response file extension and mime type Swagger integration: Automatic mock creator for web-services with swagger definition Platform independent mocks: Mock any service irrespective of the language it is written in Server states: Ability to mock server state Support for Mobile applications: Ability to mock services for mobile applications Manual tests against mock service: Ability to run tests manually against mock servicePlanned features Ability to specify various data storage for mock data Auto-refresh of data Network and Test APIs to support instrumentation Debugging tool to help development by supporting auto-replay of data Support to auto-generate endpoint URLs for mocking Support for changing mocked data via UI",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Introduction"
},
"documentation-mocking-services-javascript-getting-started": {
"title": "Getting Started",
"content": "Pre-Requisite Please install the latest Node.jsSetting Mock ServerTo set up mock server, you need only three things: Install mock-server module. Routes for mock-server. Script to start mock-server.Follow the steps below to set-up mock server: Create a new directory mock-server. Create a new file package.json under mock-server directory. Add Mock Server module dependency in package.json as shown below. { \"name\": \"test-midway\", \"dependencies\": { \"testarmada-midway\": \"^1.0.1\" }, \"scripts\": { \"start-mock\": \"node mocks/run-mock-server-console.js\" } } Create another directory mocks under the mock-server directory. Under the directory mocks, create a file endpoints.js with the following code - This file will contain the routes that you want to mock var midway = require('testarmada-midway'); // Required midway.id('example'); // Required // add a route that returns a message \"hello world\" midway.route({ id: 'message', label: 'hello message', path: '/message', method: 'GET', variantLabel: 'hello world', handler: function(req, reply) { reply({message: 'hello world'}); } }); Under the directory mocks, create a file run-mock-server-console.jswith the following code - This file will contain the start-up script for mock server // load mocked endpoint require('./endpoints'); var midway = require('testarmada-midway'); midway.start({ host: 'localhost', mockedDirectory: './mocks', // this can be provided as an absolute path as well. port: 8080, project: 'HelloMidway', //Replace HelloMidway with your project name (without dashes). }); Now open terminal/cmd prompt and navigate to the directory mock-server and run the following command to install Mock Server and dependencies: npm install Starting Mock Server To start mock-server use the following command and than go to http://localhost:8080/midway for mock-server admin-ui. npm run start-mock Common Use Cases Starting mock server on HTTPS port - To enable https, add httpsPort with the desired port number in server start script as shown below: midway.start({ port: 8080, httpsPort: 4444, host: 'localhost', mockedDirectory: './test/resources/mocked-data', project: 'HelloMidway' }); Mocking different REST methods - To mock different rest methods, change the method value in the midway.route() object to any one of the following desired values: POST GET PUT DELETE OPTIONS PATCH Returning different data set for the same mocked route (Variants) - Variants allows to return a different set of data for the same mocked route. To add one or more variants, attach the variant object to midway.route() as shown below: midway.route({ id: 'message', label: 'Hello message', path: '/message', method: 'GET', variantLabel: 'hello world', handler: function (req, reply) { reply({message:'Hello World'}) } }) .variant({ id: 'universe', label: 'hello universe', handler: function (req, reply) { reply({message:'hello universe'}) } }) .variant({ id: 'universe', label: 'hello galaxy', handler: function (req, reply) { reply({message:'Hello Galaxy'}) } }); To get a different set of response, go to admin-ui and select a different variant for the above route and hit http://localhost:8080/message on your favorite browser. Storing mocked response in a file - This feature allows you to respond with a static data stored in a file instead of hard coding the response data in the routes definition. // Automatic reply of the file midway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/test', method: 'GET', variantLabel: 'test-1', handler: function(req, reply) { midway.util.respondWithFile(this, reply); } }) .variant({ id: 'universe', label: 'test-2', handler: function (req, reply) { midway.util.respondWithFile(this, reply); } }); In the above setup, file needed for default route handler (test-1) should be located at (file location/name is based on mockedDirectory/route/method/[default|variant_name].{ext}) ./mocks/product/grouping/api/collection/GET/default.{ext} If this would be a POST call than the file should have been at ./mocks/product/grouping/api/collection/POST/default.{ext} The file name for variants should change from default.{ext} to universe.{ext} in above example that is the file name should be the variant name. Directing Traffic To Mock ServerTo mock live services, your application should allow to configure it to be directed to a mock service instead of live services as shown below:Please update your app server or application by changing the host name of your live service with the host name for your mock server.Mock Server Set-up Flow Identify REST endpoints that needs to be mocked. Gather mocked data for those REST endpoints. Create Mocked Routes by adding them in endpoints.js file. Start Mock Server. Start Your Application server that points to the Mock Server host name instead of live-service. Run your application and the mocked data will be returned for mocked routes.",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Getting Started"
},
"documentation-mocking-services-javascript-faq": {
"title": "FAQ",
"content": "What Can Be Mocked?Any Restful service API can be mocked such as: GET POST PUT DELETE OPTIONS and so on..Can AJAX Calls Be Mocked?Yes - It is same as for any other backend service. For AJAX call, point it to the mocked server instance instead of the actual back end service and add a mocked route in the file containing mocked routes for mock server.What Are The Pre-Requisites? node.js 4+ (npm is included in the package)How Can I Add Mock Server Dependency To My Node Project?\"dependencies\": { \"testarmada-midway\": \"1.0.1\" // add the latest version}How To Add A Mocked Route?Add the following code in your routes file, typically endpoints.jsmidway.route({ id: 'helloWorld', // required label: 'Hello World', // Used for Mock Server UI path: '/helloWorld', // the path you want to mock method: 'GET', // The Rest Method you want to mock for this API handler: function (req, reply) { // Add Logic to massage data before returning back to the request. reply('Hello World'); }});How To Create Dynamic URLs?By adding the URL part in curly brackets that you would liek to by dynamic such as /get/customerInfo/{customerid}/{zipcode}For example:midway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}/{zipcode}', // both customerid and zipcode will be dynamic method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { reply('How to read the customer id :('); }});How To Read Dynamic URLs In Request?var midway = require('testarmada-midway');midway.route({ path: '/get/customerInfo/{customerid}/{zipcode}' handler: function(request, reply) { var params = request.params; var customerid = params.customerid; // customerid is 123 if request is \"/get/customerInfo/123/92127\" var zipcode = params.zipcode; // zipcode is 92127 if request is \"/get/customerInfo/123/92127\" }}); How To Read Header Parameters In Request?var midway = require('testarmada-midway');midway.route({ path: '/api/getCart' handler: function(request, reply) { var headers = request.raw.req.headers; var authorization = headers.authorization; }}); How To Read Payload In Request?var midway = require('testarmada-midway');midway.route({ path: '/api/getCart' handler: function(request, reply) { var payload = request.payload; // foo would be \"bar\" if the posted body content (as JSON) is {\"foo\": \"bar\"} var foo = payload.foo; }}); How To Read Query Parameters In Request?var midway = require('testarmada-midway');midway.route({ path: '/api/getCart' handler: function(request, reply) { var queryParams = request.query; // foo would be \"bar\" if incoming request is \"/api/getCart?foo=bar\" var foo = queryParams.foo; }}); How To Set Custom Headers In Mocked Response?Preferred Waymidway.route({ id: 'header', label: 'Test Headers', path: '/api/testHeaders', handler: function (req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; midway.util.respondWithFile(this, reply, {headers: myHeaders}); }});Alternate Waymidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { reply({message: 'test'}) .header('X-Res-Header', 'I\\'m a custom response header') }});How To Set Custom Cookies In Mocked Response?Preferred Waymidway.route({ id: 'cookie', label: 'Test Cookies', path: '/api/testCookies', handler: function (req, reply) { var cookies = [ {name: 'com.wm.customer', value: 'vz7.0b5c56'}, {name: 'CID', value: 'SmockedCID', options: {domain: 'domain', path: '/'}}, {name: 'anotherCookie', value: 'cookieValue'} ]; midway.util.respondWithFile(this, reply, {cookies: cookies}); }});Alternate Waymidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { reply({message: 'test'}) .state('test-cookie', 'I\\'m a custom response cookie') }}); How To Set CORS Headers?var corsHeaders = { origin: ['*'], headers: [\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept\"], credentials: true,}// Itemsmidway.route({ id: 'tempo', label: 'Tempo', path: '/tempo1', config: { cors: corsHeaders }, handler: function(req, reply) { midway.util.respondWithFile(this, reply); }});What Is respondWithFile Utility?This feature allows you to respond with a data stored in a file instead of hard coding the response data in the routes definition. This way user does not have to hard-code/change the response in handler and rather can just swap the file with different data without even bringing the server down. midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); } });In the above example, mock server will automatically look for a file default.{some_extension} at ./mocked-data/get/fromFile/GET/default.{some_extension}How File Path Is Calculated For respondWithFile Utility?The path to the mocked data file is auto-calculated based on the route path. For example if the route path is /get/cart than for the default variant, mock server will look for the default.{some_extension} file at ./mocked-data/get/fromFile/GET/default.{some_extension}. For variants, the name of the file should be changed from default to the variant name as shown below:midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }}).variant({ id: 'textData', label: 'Text Data', handler: function (req, reply) { midway.util.respondWithFile(this, reply); }});In above example mock server will look for ./resources/mocked-data/get/fromFile/GET/textData.{some_extension} file for the variant textDataCan I Provide A Custom File Location respondWithFile Utility?Yes. By adding filePath parameter as shown in below example:midway.route({ id: 'CustomResponseFile', label: 'Response From Custom Path', path: '/get/customFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {filePath: './custom.json'}); }});In above example mock server will look for the file under MockedDirectory only but at ./mocked-data/custom.jsonHow To Respond Only With Code?midway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { reply().code(400); }});Can I Return A Response Code With respondWithFile Utility?Yes - by adding code parameter as shown in below example:midway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400}); }});What Is MockedDirectory Path?Mocked directory path is the location to the base directory where all your mocked response file will be stored. This parameter is defined in run-mock-server-console.js file. It is defined at the start of mock server as shown in the code below:require('./endpoints');require('testarmada-midway').start({ host: \"localhost\", mockedDirectory: \"./resources/mocked-data\", port: 8000, project: 'HelloMidway'});Location For Response File For RespondWithFile?If you have set your default folder to be mocked-data, then based on your URL path:For default variant, mock server will look for ./mocked-data/product/grouping/api/collection/GET/default.json and for mixItem variant mock server will look for ./mocked-data/product/grouping/api/collection/GET/mixItem.jsonWhat Are Variants?Variants allows to return a different data set for a given mocked route. Variants can be selected either in the admin UI or through automation APIs to determine what type of response a route should have. Routes are defined using the variant method on the Route object (returned by calling the route method). An object parameter is provided with the following attributes id: the variant id - used for the RESTful admin API and profile settings label: (optional) the variant label - used for display on the admin panel handler: (optional) the HAPI route handler which provides the route responseVariants are useful because they allow you to test multiple scenarios that can happen with your route. Say, for example, you have a route exposing the ability to update a password. You might have several exceptional scenarios that you would want to test out (each could be a variant that you simply select to tell the route handler to use the appropriate response) the password was reset successfully the password didn’t pass validation the old password wasn’t entered correctly the username doesn’t exist and so on…How To Add A Variant To A Route?To add a one or more variants do the following:midway.route({ id: 'message', label: 'Message', path: '/get/message', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { reply('Hello'); }}) .variant({ id: 'hello', label: 'Hello World', handler: function (req, reply) { reply('Hello World'); } }).variant({ id: 'hello', label: 'Hello Universe', handler: function (req, reply) { reply('Hello Universe'); } }); How To Switch Variants In Test Case?browser.setMockVariant({ fixture: \"fixture id\", variant: \"variant id\" }); How To Switch Variants With HTTP Call?You can also switch the variants via HTTP call (Recommended only when not using Midway as a library). As an example, if you want to set variant to helloUniverse for the route below: midway.route({ id: 'helloWorld', label: 'Hello World', path: '/helloWorld', method: 'GET', handler: function (req, reply) { reply('Hello World'); } }) .variant({ id: 'helloUniverse', label: 'Hello Universe', handler: function (req, reply) { reply('Hello Universe'); } });curl -H \"Content-type: application/json\" -X POST -d '{\"variant\":\"<variant>\"}' <host>:<port>/midway/api/route/<routeId>So for the above route, you can switch the variant to helloUniverse like this:curl -H \"Content-type: application/json\" -X POST -d '{\"variant\":\"helloUniverse\"}' http://localhost:8000/midway/api/route/helloWorldWhen using parallel sessions, if you want to switch a variant for a route for a particular session, register the session with mock server like this:curl <host>:<port>/midway/api/registerSession// e.g curl http://localhost:8000/midway/api/registerSessionIf sessions are available, mock server will return a response like: {\"session\":\"33b08d\"}Extract the session id from response and append it to the route id you want to switch variant for e.g:curl -H \"Content-type: application/json\" -X POST -d \"variant\":\"helloUniverse\"}' http://localhost:8000/midway/api/route/helloWorld-33b08dWhat Is Mock Server UI Used For?UI can be used to view and test mocked routes as well as for manual switching of variants when running tests manually.What Is Parallel Sessions?Parallel sessions allows you to run multiple instance of server virtually while running only one server. This is helpful when you are running multiple test cases which access the same routes but different variants as parallel sessions allow you to set different variants on same routes without conflicting. This saves CPU and RAM both as only one server is running instead of multiple. Please see the call flow explaination without and with Parallel Sessions Below:Call Flow Without Parallel SessionsCall Flow With Parallel SessionsHow Can I Enable Parallel Sessions On Mock Server?Add sessions parameter with number of virtual services you want as shown in below example while startung mock Server.require('./endpoints');var midway = require('testarmada-midway');midway.start({ host: \"localhost\", mockedDirectory: \"./resources/mocked-data\", port: 8000, sessions: 2, project: 'HelloMidway'});How Can I Register a Session For Parallel Sessions?var sessionId = midway.registerSession();How Can I Close A Session For Parallel Sessions?var closeSession = midway.closeSession(sessionId);Does Mock Server Has Any Utility To Modify JSON Data Stored In Files?Yes - Mock Server exposes transpose option that cna be passed in respondWithFile method to modify the JSON files dynamically.How Does transposeData Work To Modify JSON Data Stored In Files?If you have many variants for a Rest end point and the mocked data for all variants can use the same JSON response with few changes to the values, than this feature is what you need. This feature allows you to dynamically change a JSON file before sending the response back from the mock server for the request. It removes the need of having one to one mapping of static JSON files with each variants.// Static Response JSON File{ id: \"1234\", name: \"toothpaste\" details: [ { flavor: \"Mint 1\", Size: \"10\", Size_Type: ounce }, { flavor: \"Mint\", Size: \"10\", Size_Type: ounce } ]}// Sample code for substituting id from 1234 to 7777 and flavor from Mint to Mint 2 for second array element in routesmidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { var dataToChange = { 'id': '7777', 'details[1].flavor': 'Mint 2' } midway.util.respondWithFile(this, reply, {transpose: dataToChange}); }});// Dynamic Response JSON File returned from Mock service{ id: \"7777\", name: \"toothpaste\" details: [ { flavor: \"Mint 1\", Size: \"10\", Size_Type: ounce }, { flavor: \"Mint 2\", Size: \"10\", Size_Type: ounce } ]}Can I Use transposeData Functionality Outside Of respondWithFile?Yes - You can use it by Midway Utils.var fileLocation = require(\"path\").join(__dirname, './resources/test-data/data-transposition-test.json');var dataSet = utils.readJsonFile(fileLocation);var dataToChange = { 'items.item[0].id': 1234, // substitue id 0001 to 1234 'items.item[0].val': \"value\", // Add 'val' to first array element of items.item 'items.item[1].id': 4567, // Add 'id' to second array element of items.item 'items.item[0].batters.batter[0].id': 5678 // substitue id 1001 to 5678}substitutedData = midway.util.transposeData(dataSet, dataToChange);// Base JSON file - data-transposition-test.json{ \"items\": { \"item\": [ { \"id\": \"0001\", \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"batters\": { \"type\" : 1, \"batter\": [ { \"id\": \"1001\", \"type\": \"Regular\" }, ] }, \"topping\": [ { \"id\": \"5001\", \"type\": \"None\" } ] } ] }};// Resulted JSON{ \"items\": { \"item\": [ { \"id\": 1234, \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"val\": \"value\" \"batters\": { \"type\": 1, \"batter\": [ {\"id\": 5678, \"type\": \"Regular\"} ] }, \"topping\": [ {\"id\": \"5001\", \"type\": \"None\"} ] }, { \"id\": 4567 } ] }};Why Mock Server Returns Error 415 Unsupported Media Type?If you’re using content type like application/graphql, follow this example midway.route({ id: 'id', label: 'id', path: '/graphql', method: ['POST', 'PUT'], config : { payload: { parse: false, allow: 'application/graphql' } }, handler: function (req, reply) { midway.util.respondWithFile(this, reply, {code: 200}); } });For more details, read this",
"url": "/documentation/Mocking/Services/JAVASCRIPT/FAQ"
},
"documentation-mocking-services-javascript-contribution-guide": {
"title": "Contribution Guide",
"content": "ArchitectureThese are the very high level components of mocking eco-system.The below diagram shows the mocking components in detail.The mocking service uses midway-smocks which provides the stateful HTTP mocking service built on top of HAPI. It allows to add routes and different scenarios for each route.In addition, the mocking service provides certain utilities via midway-util. It also provides logging facility with midway-loggerMock Server Start flowThe mocking service exposes its features via API’s and HTTP end points. Lets take a look at the sequence of events when the mock server is started.In the above diagram, the actor can be the test code which starts mock server or a developer using the mock service for local development / testing. Users can specify what routes to mock by specifying them in endpoints.js Midway’s start() is invoked with options to start the Midway server Midway creates an instance of Hapi server Midway adds the routes for the system API’s it supports Midway gets the plugin from midway-smocks Midway registers the plugin it obtained from the above step Midway starts the server Once the Midway server is started, you can use the Midway API’s via HTTP Calls or libraries [Read API Guide for examples] Parallel vs non-parallel sessionsWithout Parallel sessionsIf we want to run two test cases in parallel, mocking the same route and returning different data, it won’t be possible with running one mock server and sharing across the whole test suite. So we needed to run one mock server and one application server per test case.With Parallel sessionsWith parallel sessions, we can share one application server and mock server for the whole test suite. It allows to mock the same route but different data for different test cases.To use parallel sessions, the mock server is started with pre-defined number of sessions. For each test, the test case needs to register a session with the mock server. The mock server returns a unique session id which is then sent as part of the request to the application server. If the request gets routed to the mock server for a mocked route, the request handler in mock server extracts the session id from the request, and prepends it to the route. For e.g, if the session id is “123”, it is prepended to the route “/api/getCart” and the route becomes “/123/api/getCart”. For another test using session id “456” , the route will become “/456/api/getCart”. This enables the mock server to be able to return two different responses for the same mocked route.Tech stackLanguage : NodejsNode Version: 4+Unit Tests: MochaCode formatting: EslintCode Coverage Report: IstanbulDeployment informationMocking components are released as npm librariesGit repository informationThe source code for all mocking components reside in Github. Midway Midway Util Midway Magellan Nightwatch Midway Logger Midway Smocks Midway SwaggerDevelopment processTo contribute to the mocking fleet, please follow these steps: Fork the repository https://github.com/TestArmada/midway. If your Github username is “abc” for e.g, your forked repository will be https://github.com/abc/midway. Clone this forked repository using git clone https://github.com/<username>/midway.git and make “midway” your working directory. Create a branch on local with git checkout -b <your branch name>. Note The default branch for all projects is development so any branch you create will be off the development branch. Install dependencies using npm install. Make the code changes in the branch you created in step (3) and write / update the unit tests to verify your changes. Run unit tests using npm test. We use eslint to ensure code formatting. This step runs both unit tests as well as verifies code formatting. We use istanbul for code coverage reporting. 95% is the minimum code coverage we expect for all our components. Once you’re ready, submit your pull request from your branch against the development branch of Midway (https://github.com/TestArmada/midway/tree/development). The PR triggers a Travis build which runs the tests in CI environment (same steps as in (5) above). Once the PR is reviewed, a team member merges the PR into the development branch. When the development branch is merged to master, a team member will push a tag to master, a Travis build is triggered and publishes a new version of the package to npm registry. Note: The same steps above are applicable for contributing to any of the mocking components.",
"url": "/documentation/Mocking/Services/JAVASCRIPT/Contribution Guide"
},
"documentation-mocking-services-javascript-api-guide": {
"title": "API Guide",
"content": " Mocking API’s Start Mock Server - start() Stop Mock Server - stop() Create Mocked Route - route() Create Variant - variant() Set variant - setMockVariant() Add global variants - addGlobalVariant() Respond With File - respondWithFile() Respond with mock variant - respondWithMockVariant() Set Mock Id - setMockId() Get Mock Id - getMockId() Reset Mock Id - resetMockId() Reset url count - resetURLCount() Get url count - getURLCount() Register session - registerSession() Close session - closeSession() Check session - checkSession() Get sessions - getSessions() Clear sessions - clearSessions() Get project name - getProjectName() Get port information - getPortInfo() Add state - addState() Get state - getState() Clear state - clearState() Enable Metrics - enableMetrics() Check if metrics are enabled - isMetricsEnabled() Dynamic transposition of JSON data - transposeData() Kill process - killProcess() Read contents of a file - readFile() Read contents of a file - readFileSynchronously() Read contents of JSON file - readJsonFile() Write to file - writeFile() Delete file - deleteFile() Check if directory exists - checkDirectoryExists() Check if file exists - checkFileExists() Set Log level - setLogLevel() Get Log level - getLogLevel() Reset Log level - resetLogLevel() Mocking API’sStart Mock Server - start()This API allows to start the mock server.midway.start(options, callback);The following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below No callback The first argument to callback function is the server instance if the start is successful, else it is an error. No where options has the following attributes: Attribute Description Required host Hostname for mock server (default: localhost) No port Port for mock server (default: 8080) No httpsPort Https port for mock server No mockedDirectory Path to the mocked data directory (default: resources/mocked-data w.r.t working directory). No sessions Number of parallel sessions to start the mock server with (default: 0) No collectMetrics Enable mock server to collect usage metrics (default: true) No project Name for your project (default: default) No Examplevar midway = require('testarmada-midway');midway.start({ host: 'localhost', port: 12000, httpsPort: 12001, mockedDirectory: '/resources/mockedData', sessions: 3, project: 'My Project'});Stop Mock Server - stop()This API allows to stop the mock server.midway.stop(server, callback);The following attributes are supported: Attribute Description Required server server instance returned by start() method Yes callback The first argument to callback function is an error if an error is encountered in stopping the server, null otherwise No Examplevar midway = require('testarmada-midway');var server = midway.start(options, callback);// do something with mock servermidway.stop(server, function (error) { if (error) { console.log('Unable to stop mock server'); } else { console.log('Mock Server stopped'); }});Create Mocked Route - route()This API allows to create/add required mocked REST endpoints.midway.route(options);The following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below Yes where options has the following attributes: Attribute Description Required id The unique route id for the mock server Yes label The route label used for display on the Midway Admin Panel No path The route path Yes method The HTTP route method (defaults to GET) No handler The HAPI route handler which provides the route response. This is optional because you could use multiple variants to handle the response (See Variants) No Examplevar midway = require('testarmada-midway');midway.route({ id: 'my_route', label: 'My Route', path: '/api/foo', method: 'GET', handler: function(request, reply) { // Add logic for handler reply('Hello'); }});Create Variant - variant()This API allows to create/add variants. Variants are route handlers that you can select manually (via Midway Admin panel) or Rest call or through Node API to select a different dataset for the response for a given route. Variants are defined using the variant() method on the Route object (returned by calling the route method).midway.route(routeOptions).variant(options)The following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below Yes where options has the following attributes: Attribute Description Required id The unique variant id for a given route Yes label The route label used for display on the Admin Panel No handler The HAPI route handler which provides the variant response for the route No Examplevar midway = require('testarmada-midway');midway.route({ id: 'my_route', path: '/api/foo', handler: function(request, reply) { // this is essentially the same as the \"default\" variant reply({firstName: 'John'}); }}).variant({ id: 'Billy', handler: function(request, reply) { reply({firstName: 'Billy'}); }}).variant({ id: 'Clark', handler: function(request, reply) { reply({firstName: 'Billy'}); }});Set variant - setMockVariant()setMockVariant can be used to set a variant to an existing API path.midway.setMockVariant(options, callback) // with Midway libraryor browser.setMockVariant(options, callback) // when using MagellanThe following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below No callback callback function to be called after setMockVariant() Yes where options has the following attributes: Attribute Description Required fixture Id defined in route Yes variant The variant defined in endpoint.js for the fixture you entered Yes portNumber Port number where the mock server is running on No midwaySessionId Midway session id, if using parallel sessions No ExampleIf the routes are defined likevar midway = require('testarmada-midway');midway.route({ id: 'hello', path: '/helloWorld', handler: function(request, reply) { reply('Hello World'); }}).variant({ id: 'universe', handler: function(request, reply) { reply('Hello Universe'); }});For the route and variant defined as above, you can set the variant to universe as follows:// when using Midway librarymidway.setMockVariant({ fixture: 'hello', // same as id in the .route() options variant: 'universe' // same as id in the .variant() options}, function (err) { if (err) { console.log('Error in setting variant:' + err); } else { console.log('Successfully set variant'); }});or // When using Magellanbrowser.setMockVariant({ fixture: \"hello\", variant: \"universe\" });or Alternately, you can also use `curl` call to set a variant with this POST call to `{host}:{port}/midway/api/route/{routeId}`curl -H \"Content-Type: application/json\" -X POST -d '{\"variant\":\"{universe}\"}' http://localhost:8080/midway/api/route/hello?returnConfig=trueYou can confirm if this works by going to Admin panel and see that for helloWorld route, the variant universe will be highlighted. Also, hitting this url http://localhost:8080/helloWorld will reply with Hello Universe.If the variant does not exist on the route, mock server returns with an Internal Server error (HTTP 500).Add global variants - addGlobalVariant()You can also add global variants that will affect all routes. The attributes to the options are same as that of variant().midway.route(routeOptions).addGlobalVariant(options)whereoptions - JSON object with the same attributes as of variant described in this sectionExamplevar midway = require('testarmada-midway');midway.addGlobalVariant({ id: '500', label: '500 error', handler: function(request, reply) { reply({ statusCode: 500, error: 'Internal Server Error' }).code(500); }})Respond With File - respondWithFile()This API allows to respond with static data stored in a file instead of hard coding the response data in the routes definition. Based on the path of the URL that is being mocked, the response file can be dropped in the directory location and the file will be automatically used by Midway for sending the response. It also allows to specify the absolute path of the response files.midway.util.respondWithFile(route, reply, options);The following attributes are supported: Attribute Description Required route Handle to the midway route object Yes reply Handle to the reply object Yes options JSON object with additional options described below No Attribute Description Required code HTTP Status code to reply with No filePath Static file path of the mocked data No delay Delay response time by this value (in milliseconds) No To use this feature, you can call respondWithFile() from inside route configuration as follows:Examplevar midway = require('testarmada-midway');// Automatic reply of the filemidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}' handler: function(req, reply) { midway.util.respondWithFile(this, reply); }}).variant({ id: 'mixItem', label: 'Mix Item' handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 204, filePath: '../mocked-data/fileName.json', delay: 1000}); }})Note the Use of midway.util to access the method respondWithFileRespond with mock variant - respondWithMockVariant()This API allows to respond with a variant on the main route handler. The ‘variant’ passed in MUST be the variant on existing route.midway.util.respondWithMockVariant(route, variant, req, reply)The following attributes are supported: Attribute Description Required route The route object Yes variant Variant on the route Yes request Request object Yes reply Reply object Yes Examplevar midway = require('testarmada-midway');midway.route({ id: 'respondWithVariant', label: 'Respond With Variant', path: '/respondWithVariant', variantLabel: 'Respond With Main Route', handler: function(req, reply) { midway.util.respondWithMockVariant(this, 'variant', req, reply); // make sure that the variant exist in the same route. }}).variant({ id: 'variant', label: 'Respond With Variant Route', handler: function(req, reply) { reply({ 'message': 'I am an example of respond_with_mock_variant instead of response of main route ' }); }});Note the Use of midway.util to access the method respondWithMockVariantSet Mock Id - setMockId()This API allows to set mock id for a given test case. If this is set, it overrides all the variants and mocked URLs responses to return mocked data from the given directory as mock-id, where mock-id is the directory name.midway.setMockId(mockId, midwaySessionId) // with Midway libraryor browser.setMockId(mocKId, midwaySessionId, callback); // when using MagellanThe following attributes are supported: Attribute Description Required mockId Mock id which is the directory name you want to respond data from Yes midwaySessionId Midway session id, if using parallel sessions No callback callback function to be invoked after mock id is set (only when using Magellan) No The file name should be in the format url-methodName-urlCount.extension for the responses stored under file. For example, for the given route belowvar midway = require('testarmada-midway');midway.route({ id: 'my_route', label: 'My Route', path: '/api/foo', method: 'GET', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }});the file name should be api-foo-GET-1.json for the first time the URL is hit. For second time the URL is hit, the file name returned would be api-foo-GET-2.json. If the specific file for the count is not present, Midway will look for default file api-foo-GET.json, which is also helpful if you want to always return the same response irrespective of the number of times the URL is hit.Example:var midway = require('testarmada-midway');midway.setMockId('cart', 'abcdef'); // All responses should be under \"cart\" directory under your mocked data directoryor browser.setMockId('cart', 'abcdef' , callback);orcurl http://localhost:8000/midway/api/setMockId/cart/abcdefTIP! For a dynamic url such as /app/{cartid}/getStatus the default file name should be app-cartid-getStatus-GET.json and the count specific file name should be like app-cartid-getStatus-GET-1.json.Get Mock Id - getMockId()This API is used to retrieve the currently set mock id.midway.getMockId(midwaySessionId);The following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No Example:var midway = require('testarmada-midway');var mockId = midway.getMockId('abcdef');or curl http://localhost:8000/midway/api/getMockId/cart/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Reset Mock Id - resetMockId()This API is used to reset currently set mock id.midway.resetMockId(midwaySessionId) // with Midway libraryor browser.resetMockId(midwaySessionId, callback); // when using MagellanThe following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No callback callback function to be invoked after mock id is set (only when using Magellan) No Example:var midway = require('testarmada-midway');midway.resetMockId('abcdef');or browser.resetMockId('abcdef', callback);or curl http://localhost:8000/midway/api/resetMockId/cart/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Reset url count - resetURLCount()This API is used to reset URL count to zero. This works in conjunction with setMockId function where you want to restart over for the URL count.midway.resetURLCount(midwaySessionId)or browser.resetURLCount(midwaySessionId, callback)The following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No callback callback function to be be invoked after the mock id is reset No Example:var midway = require('testarmada-midway');midway.resetURLCount('abcdef');or browser.resetCount('abcdef', callback); // 'abcdef' is a midway session id in use for the testorcurl http://localhost:8000/midway/api/resetURLCount/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Get url count - getURLCount()This API is used in conjunction with setMockId function where you want to get the URL count for all mocked calls.midway.getURLCount(midwaySessionId)The following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No Example:var midway = require('testarmada-midway');midway.getURLCount('abcdef');or curl http://localhost:8000/midway/api/getURLCount/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Register session - registerSession()This API is used to register a session with Midway for a test case when using parallel sessions. Midway needs to be started with sessions.midway.registerSession(); // with Midway libraryor browser.registerSession(callback); // with browser testsThe following attributes are supported: Attribute Description Required callback callback function to be be invoked after the session is registered. First argument to the callback is an error object, in case of error, null otherwise. The second argument is the registered session id (Only for browser tests) Yes You can use registerSession() to register a session with Midway and can subsequently use that session id for the current test. Midway returns a unique identifier when registering a session.If no session is available to use, Midway returns with the message NOT_AVAILABLE.ExampleIf midway server is started with sessions, for e.g 3 sessions as shown below,var midway = require('testarmada-midway');midway.start({ host: 'localhost', port: 8080, mockedDirectory: 'resources/mockedData', sessions: 3});var midwaySessionId = midway.registerSession();or browser.registerSession(function (err, sessId) { if (err) { return callback(new Error(\"Unable to get the sessionId\")); } self.midwaySessionId = sessId; client.midwaySessionId = sessId; return callback();});orcurl http://localhost:8000/midway/api/registerSessionClose session - closeSession()This API is used to close a session after running a test so it can be made available for subsequent tests.midway.closeSession(midwaySessionId);or browser.closeSession(midwaySessionId, callback);The following attributes are supported: Attribute Description Required midwaySesssionId Midway session id to be closed Yes callback callback function to be be invoked after the session is registered. First argument to the callback is an error object, in case of error, null otherwise (Only when using browser tests) Yes Examplevar midway = require('testarmada-midway');midway.closeSession('abcdef'); // abcdef is a previously registered session with Midwayor client.closeSession('abcdef', function (err) { if (err) { console.error(\"Error in closing session:\"); }});orcurl http://localhost:8000/midway/api/closeSession/abcdefNote that abcdef is a previously registered session with Midway.Check session - checkSession()This API is used to check status of a session id. It returns one of these states AVAILABLE - If the session is available for use IN_USE - If the session is in use DOES_NOT_EXISTS - If the session id passed is invalid or does not existThe following attributes are supported: Attribute Description Required midwaySessionId Midway session id Yes Examplevar midway = require('testarmada-midway');var status = midway.checkSession('abcdef');or curl http://localhost:8000/midway/api/checkSession/abcdefGet sessions - getSessions()This API is used to get sessions informationmidway.getSessions();Examplevar midway = require('testarmada-midway');var status = midway.getSessions();or curl http://localhost:8000/midway/api/getSessionsClear sessions - clearSessions()This API is used to clear the sessions information.midway.clearSessions();Examplevar midway = require('testarmada-midway');var status = midway.clearSessions();Get project name - getProjectName()This API is used to get the project name passed in Midway optionsmidway.getProjectName();Examplevar midway = require('testarmada-midway');var projectName = midway.getProjectName();Get port information - getPortInfo()This API is used to get the port information passed in Midway optionsmidway.getPortInfo();Examplevar midway = require('testarmada-midway');var portInfo = midway.getPortInfo();Add state - addState()This API is used to add a value to the server state.midway.addState(route, key, value);The following attributes are supported: Attribute Description Required route Route object Yes key Key for the state variable Yes value Value of the state variable Yes Examplevar midway = require('testarmada-midway');midway.route({ id: 'setState', label: 'Add State', path: '/login', handler: function (req, reply) { midway.addState(this, 'loggedIn', true); reply().code(204); }});Get state - getState()This API is used to read a value from the server state.midway.getState(route, key);The following attributes are supported: Attribute Description Required route Route object Yes key Key for the state variable Yes Examplevar midway = require('testarmada-midway');midway.route({ id: 'getState', label: 'Get State', path: '/isLogin', handler: function (req, reply) { var isLoggedIn = midway.getState(this, 'login'); reply(isLoggedIn); }});Clear state - clearState()This API is used to clear a state for a given session id (Defaults to default session).midway.clearState(midwaySessionId);The following attributes are supported: Attribute Description Required midwaySessionId Midway session id No Examplevar midway = require('testarmada-midway');midway.clearState(); // Clears state for default sessionmidway.clearState('abcdef') // Clears state for session id `abcdef`Enable Metrics - enableMetrics()This API is used to enable gathering of usage metrics.midway.enableMetrics(boolean);The following attributes are supported: Attribute Description Required boolean true to enable, false to disable No Examplevar midway = require('testarmada-midway');midway.enableMetrics(true); // Enables gathering of usage metricsmidway.enableMetrics(false); // Disables gathering of usage metricsCheck if metrics are enabled - isMetricsEnabled()This API is used to check if metrics gathering is enabled on Midway. Returns true if metrics gathering is enabled, false otherwisemidway.isMetricsEnabled();Examplevar midway = require('testarmada-midway');midway.isMetricsEnabled();Dynamic transposition of JSON data - transposeData()This API allows to dynamically transpose the JSON datamidway.util.transposeData(dataSet, dataToChange);The following attributes are supported: Attribute Description Required dataSet The data set which needs to change Yes dataToChange The changes needed in the data set Yes To change the JSON data on fly (edit existing values or add values).// Base JSON file{ \"items\": { \"item\": [ { \"id\": \"0001\", \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"batters\": { \"type\" : 1, \"batter\": [ { \"id\": \"1001\", \"type\": \"Regular\" }, ] }, \"topping\": [ { \"id\": \"5001\", \"type\": \"None\" } ] } ] }}// Code examplevar dataToChange = { 'items.item[0].id': 1234, // substitue id 0001 to 1234 'items.item[0].val': \"value\", // Add 'val' to first array element of items.item 'items.item[1].id': 4567, // Add 'id' to second array element of items.item 'items.item[0].batters.batter[0].id': 5678 // substitue id 1001 to 5678}// when using utils classvar fileLocation = require(\"path\").join(__dirname, './resources/test-data/data-transposition-test.json');var dataSet = utils.readJsonFile(fileLocation);substitutedData = midway.util.transposeData(dataSet, dataToChange);// When using with respondwithFile (This will read the file based on url path and transpose the data)midway.util.respondWithFile(this, reply, {transpose: dataToChange});// Resulted JSON{ \"items\": { \"item\": [ { \"id\": 1234, \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"val\": \"value\" \"batters\": { \"type\": 1, \"batter\": [ {\"id\": 5678, \"type\": \"Regular\"} ] }, \"topping\": [ {\"id\": \"5001\", \"type\": \"None\"} ] }, { \"id\": 4567 } ] }}Note the Use of midway.util to access the method transposeDataKill process - killProcess()This API allows to Kill a process with a pidmidway.util.killProcess(pid, signal, callback);The following attributes are supported: Attribute Description Required pid process id to kill Yes signal Signal to send (defaults to SIGKILL if passed undefined) Yes callback Callback function after killprocess completes No Examplevar midway = require('testarmada-midway');midway.util.killProcess(18222, 'SIGKILL', function () { console.log('Process killed);});Note the Use of midway.util to access the method killProcessRead contents of a file - readFile()This API allows to read contents of a file asynchronouslymidway.util.readFile(filePath, callback);The following attributes are supported: Attribute Description Required file path Absolute or relative location of file Yes callback Callback function after file is read. If file is read successfully, the second argument is the file data. In case of error, the first argument is an error. Returns promise if callback is omitted No Examplevar midway = require('testarmada-midway');midway.util.readFile('data.json', function (err, fileData) { if (err) { console.log('Error in reading file ', err); } else { console.log(fileData); }});Note the Use of midway.util to access the method readFileRead contents of a file - readFileSynchronously()This API allows to read contents of a file synchronouslymidway.util.readFileSynchronously(filePath);The following attributes are supported: Attribute Description Required file path Absolute or relative location of file Yes Examplevar midway = require('testarmada-midway');midway.util.readFileSynchronously('data.json');Note the Use of midway.util to access the method readFileSynchronouslyRead contents of JSON file - readJsonFile()This API allows to read contents of a JSON file synchronouslymidway.util.readJsonFile(filePath);The following attributes are supported: Attribute Description Required file path Absolute or relative location of JSON file Yes Examplevar midway = require('testarmada-midway');midway.util.readJsonFile('data.json');Note the Use of midway.util to access the method readJsonFileWrite to file - writeFile()This API allows to write file contents to a filemidway.util.writeFile(filePath, file data, callback);The following attributes are supported: Attribute Description Required file path Absolute or relative location of file Yes file data contents to write Yes callback Callback function after writeFile completes Yes Examplevar midway = require('testarmada-midway');midway.util.writeFile('hello.txt', 'hello world blah blah', function () { console.log('Wrote to file successfully');});Note the Use of midway.util to access the method writeFileDelete file - deleteFile()This API allows to write file contents to a filemidway.util.deleteFile(filePath, callback);The following attributes are supported: Attribute Description Required file location Absolute or relative location of file to delete Yes callback Callback function after deleteFile completes Yes Examplevar midway = require('testarmada-midway');midway.util.deleteFile('filetoDelete.txt', function (err) { if (err) { console.log('Error in deleting file'); }});Note the Use of midway.util to access the method deleteFileCheck if directory exists - checkDirectoryExists()This API allows to check if a directory exists. Returns true if directory exists, false otherwise.midway.util.checkDirectoryExists(directoryPath);The following attributes are supported: Attribute Description Required directory path Location of directory to check Yes Examplevar midway = require('testarmada-midway');midway.util.checkDirectoryExists('/home/data');Note the Use of midway.util to access the method checkDirectoryExistsCheck if file exists - checkFileExists()This API allows to check if a file exists. Returns true if file exists, false otherwise.midway.util.checkFileExists(filePath);The following attributes are supported: Attribute Description Required file path Location of file to check Yes Examplevar midway = require('testarmada-midway');midway.util.checkFileExists('/home/data');Note the Use of midway.util to access the method checkFileExistsSet Log level - setLogLevel()This API allows to set log level on Midwaymidway.log.setLogLevel(logLevel); // when using MidwayorLogger.setLogLevel(logLevel); // when using Midway-LoggerThe following attributes are supported: Attribute Description Required logLevel Log level you want to set .Valid values (warn/info/debug/error) Yes Examplevar midway = require('testarmada-midway');midway.log.setLogLevel('debug');orcurl -X GET http://localhost:8080/midway/api/setloglevel/debugGet Log level - getLogLevel()This API allows to get the current log level on Midwaymidway.log.getLogLevel(); // when using Midwayor Logger.getLogLevel(); // when using Midway-LoggerExamplevar midway = require('testarmada-midway');midway.log.getLogLevel();orvar Logger = require('testarmada-midway'-logger');Logger.getLogLevel();orcurl -X GET http://localhost:8080/midway/api/getloglevelReset Log level - resetLogLevel()This API allows to reset the log level of Midway to info (Default log level)midway.log.resetLogLevel();or Logger.resetLogLevel();Examplevar midway = require('testarmada-midway');midway.log.resetLogLevel();orvar Logger = require('testarmada-midway'-logger');Logger.resetLogLevel();or curl -X GET http://localhost:8080/midway/api/resetloglevel",
"url": "/documentation/Mocking/Services/JAVASCRIPT/API Guide"
},
"documentation-mocking-native-ios-javascript-training-guide": {
"title": "Training Guide",
"content": "120 minMocking 101Covered topicsUnderstand of mocking solution and it's featuresHow to set up and start mock serverBasic usage of mocking solution's functionalitiesStart120 minMocking 201Covered topicsLearn creating dynamic URLsRead various REST call request informationCustomize mocked responseStart120 minMocking 301Covered topicsReturning responseSetMockId and APIs for itParallel SessionsStart120 minMocking 401Covered topicsMaintain states in mock serverMocking utility methodsSupported Rest APIs for mock serverStart",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Training Guide/"
},
"documentation-mocking-native-ios-javascript-introduction": {
"title": "Introduction",
"content": "Why Use Mock Server?Most of the applications rely on one or many back end services. For successful test execution and fast development, all the dependent backend services should be reliable 100% of the time. However that is not possible as the backend services may be down from time to time for various reasons or may have data inconsistency issues which makes testing/development against live services inefficient and time consuming.To overcome above mentioned limitations, our mocking solution can be used to quickly stub the API responses that are used by your application.We provide a mocking solution which can be leveraged to quickly stub the REST API responses that are used by your application during development or testing. The application points to the mock service host address instead of the live service. Pre-recorded responses are then returned for various endpoints from the mock service. Since there is minimal logic when writing mock service, maintenance and development cost for mock service is minimal. Some of the major development pain-points addressed by the mocking solution are: Unstable services - Teams have saved upto 12 hours/week of development as well as testing time due to downtime / instability of external services. Inconsistent Data - Teams have reduced the test data setup time by about 27 hours/week by eliminating the dependency on external teams for test data setup. Test flakiness - Teams have reduced test flakiness by about 25% Test against negative or unreal scenarios - Teams have reported to have increase test coverage for negative scenarios from no tests before to upto 15 test cases now by simulating service faults deterministicallySome of the key features of the mocking solution are: Ease of setup - Very easy to setup mocked data and use it while development or testing your application Drop and Respond - Respond with a JSON file based on the url route path automatically by dropping JSON response file in folder mapping to url path Test Reuse - ability to execute test cases against mock or live serviceThe mocking solution helps the teams develop and test their web and mobile applications in local as well as CI environments.Feature list Ease of setup - Very easy to setup mocked data and use it while development or testing your application Test Reuse: Execute same test cases against mock or live service. Drop-And-Respond: Respond with a JSON file based on the url route path automatically by dropping json response file in folder mapping to url path. Test De-coupling: No coupling with test cases - Test cases are independent of mock implementation except that setting the desired response for the mock service (which has no impact if the test case is run against a live service). Respond with mocked data from a directory: Mocked data response from specific directory irrespective of Rest APIs Common Utilities: Common utility methods are provided as part of the mocking service which allows quicker test development. UI Interface: Mock service UI for manual testing/debugging. HTTPS Support: HTTPS support for all the urls. Parallel Sessions: Support for single instance mock server for parallel processes Shared Mock data: Allows fetching of mocked data and routes from multiple Git repositories Magellan/Nightwatch integration: Ability to use mocking service with Magellan tests Dynamic Transposition of Mock Data (JSON): Ability to modify response on the fly Support for all file types: Auto evaluation of response file extension and mime type Swagger integration: Automatic mock creator for web-services with swagger definition Platform independent mocks: Mock any service irrespective of the language it is written in Server states: Ability to mock server state Support for Mobile applications: Ability to mock services for mobile applications Manual tests against mock service: Ability to run tests manually against mock servicePlanned features Ability to specify various data storage for mock data Auto-refresh of data Network and Test APIs to support instrumentation Debugging tool to help development by supporting auto-replay of data Support to auto-generate endpoint URLs for mocking Support for changing mocked data via UI",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Introduction"
},
"documentation-mocking-native-ios-javascript-getting-started": {
"title": "Getting Started",
"content": "Pre-Requisite Please install the latest Node.jsSetting Mock ServerTo set up mock server, you need only three things: Install mock-server module. Routes for mock-server. Script to start mock-server.Follow the steps below to set-up mock server: Create a new directory mock-server. Create a new file package.json under mock-server directory. Add Mock Server module dependency in package.json as shown below. { \"name\": \"test-midway\", \"dependencies\": { \"testarmada-midway\": \"^1.0.1\" }, \"scripts\": { \"start-mock\": \"node mocks/run-mock-server-console.js\" } } Create another directory mocks under the mock-server directory. Under the directory mocks, create a file endpoints.js with the following code - This file will contain the routes that you want to mock var midway = require('testarmada-midway'); // Required midway.id('example'); // Required // add a route that returns a message \"hello world\" midway.route({ id: 'message', label: 'hello message', path: '/message', method: 'GET', variantLabel: 'hello world', handler: function(req, reply) { reply({message: 'hello world'}); } }); Under the directory mocks, create a file run-mock-server-console.jswith the following code - This file will contain the start-up script for mock server // load mocked endpoint require('./endpoints'); var midway = require('testarmada-midway'); midway.start({ host: 'localhost', mockedDirectory: './mocks', // this can be provided as an absolute path as well. port: 8080, project: 'HelloMidway', //Replace HelloMidway with your project name (without dashes). }); Now open terminal/cmd prompt and navigate to the directory mock-server and run the following command to install Mock Server and dependencies: npm install Starting Mock Server To start mock-server use the following command and than go to http://localhost:8080/midway for mock-server admin-ui. npm run start-mock Common Use Cases Starting mock server on HTTPS port - To enable https, add httpsPort with the desired port number in server start script as shown below: midway.start({ port: 8080, httpsPort: 4444, host: 'localhost', mockedDirectory: './test/resources/mocked-data', project: 'HelloMidway' }); Mocking different REST methods - To mock different rest methods, change the method value in the midway.route() object to any one of the following desired values: POST GET PUT DELETE OPTIONS PATCH Returning different data set for the same mocked route (Variants) - Variants allows to return a different set of data for the same mocked route. To add one or more variants, attach the variant object to midway.route() as shown below: midway.route({ id: 'message', label: 'Hello message', path: '/message', method: 'GET', variantLabel: 'hello world', handler: function (req, reply) { reply({message:'Hello World'}) } }) .variant({ id: 'universe', label: 'hello universe', handler: function (req, reply) { reply({message:'hello universe'}) } }) .variant({ id: 'universe', label: 'hello galaxy', handler: function (req, reply) { reply({message:'Hello Galaxy'}) } }); To get a different set of response, go to admin-ui and select a different variant for the above route and hit http://localhost:8080/message on your favorite browser. Storing mocked response in a file - This feature allows you to respond with a static data stored in a file instead of hard coding the response data in the routes definition. // Automatic reply of the file midway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/test', method: 'GET', variantLabel: 'test-1', handler: function(req, reply) { midway.util.respondWithFile(this, reply); } }) .variant({ id: 'universe', label: 'test-2', handler: function (req, reply) { midway.util.respondWithFile(this, reply); } }); In the above setup, file needed for default route handler (test-1) should be located at (file location/name is based on mockedDirectory/route/method/[default|variant_name].{ext}) ./mocks/product/grouping/api/collection/GET/default.{ext} If this would be a POST call than the file should have been at ./mocks/product/grouping/api/collection/POST/default.{ext} The file name for variants should change from default.{ext} to universe.{ext} in above example that is the file name should be the variant name. Directing Traffic To Mock ServerTo mock live services, your application should allow to configure it to be directed to a mock service instead of live services as shown below:Please update your app server or application by changing the host name of your live service with the host name for your mock server.Mock Server Set-up Flow Identify REST endpoints that needs to be mocked. Gather mocked data for those REST endpoints. Create Mocked Routes by adding them in endpoints.js file. Start Mock Server. Start Your Application server that points to the Mock Server host name instead of live-service. Run your application and the mocked data will be returned for mocked routes.",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Getting Started"
},
"documentation-mocking-native-ios-javascript-faq": {
"title": "FAQ",
"content": "What Can Be Mocked?Any Restful service API can be mocked such as: GET POST PUT DELETE OPTIONS and so on..Can AJAX Calls Be Mocked?Yes - It is same as for any other backend service. For AJAX call, point it to the mocked server instance instead of the actual back end service and add a mocked route in the file containing mocked routes for mock server.What Are The Pre-Requisites? node.js 4+ (npm is included in the package)How Can I Add Mock Server Dependency To My Node Project?\"dependencies\": { \"testarmada-midway\": \"1.0.1\" // add the latest version}How To Add A Mocked Route?Add the following code in your routes file, typically endpoints.jsmidway.route({ id: 'helloWorld', // required label: 'Hello World', // Used for Mock Server UI path: '/helloWorld', // the path you want to mock method: 'GET', // The Rest Method you want to mock for this API handler: function (req, reply) { // Add Logic to massage data before returning back to the request. reply('Hello World'); }});How To Create Dynamic URLs?By adding the URL part in curly brackets that you would liek to by dynamic such as /get/customerInfo/{customerid}/{zipcode}For example:midway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}/{zipcode}', // both customerid and zipcode will be dynamic method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { reply('How to read the customer id :('); }});How To Read Dynamic URLs In Request?var midway = require('testarmada-midway');midway.route({ path: '/get/customerInfo/{customerid}/{zipcode}' handler: function(request, reply) { var params = request.params; var customerid = params.customerid; // customerid is 123 if request is \"/get/customerInfo/123/92127\" var zipcode = params.zipcode; // zipcode is 92127 if request is \"/get/customerInfo/123/92127\" }}); How To Read Header Parameters In Request?var midway = require('testarmada-midway');midway.route({ path: '/api/getCart' handler: function(request, reply) { var headers = request.raw.req.headers; var authorization = headers.authorization; }}); How To Read Payload In Request?var midway = require('testarmada-midway');midway.route({ path: '/api/getCart' handler: function(request, reply) { var payload = request.payload; // foo would be \"bar\" if the posted body content (as JSON) is {\"foo\": \"bar\"} var foo = payload.foo; }}); How To Read Query Parameters In Request?var midway = require('testarmada-midway');midway.route({ path: '/api/getCart' handler: function(request, reply) { var queryParams = request.query; // foo would be \"bar\" if incoming request is \"/api/getCart?foo=bar\" var foo = queryParams.foo; }}); How To Set Custom Headers In Mocked Response?Preferred Waymidway.route({ id: 'header', label: 'Test Headers', path: '/api/testHeaders', handler: function (req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; midway.util.respondWithFile(this, reply, {headers: myHeaders}); }});Alternate Waymidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { reply({message: 'test'}) .header('X-Res-Header', 'I\\'m a custom response header') }});How To Set Custom Cookies In Mocked Response?Preferred Waymidway.route({ id: 'cookie', label: 'Test Cookies', path: '/api/testCookies', handler: function (req, reply) { var cookies = [ {name: 'com.wm.customer', value: 'vz7.0b5c56'}, {name: 'CID', value: 'SmockedCID', options: {domain: 'domain', path: '/'}}, {name: 'anotherCookie', value: 'cookieValue'} ]; midway.util.respondWithFile(this, reply, {cookies: cookies}); }});Alternate Waymidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { reply({message: 'test'}) .state('test-cookie', 'I\\'m a custom response cookie') }}); How To Set CORS Headers?var corsHeaders = { origin: ['*'], headers: [\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept\"], credentials: true,}// Itemsmidway.route({ id: 'tempo', label: 'Tempo', path: '/tempo1', config: { cors: corsHeaders }, handler: function(req, reply) { midway.util.respondWithFile(this, reply); }});What Is respondWithFile Utility?This feature allows you to respond with a data stored in a file instead of hard coding the response data in the routes definition. This way user does not have to hard-code/change the response in handler and rather can just swap the file with different data without even bringing the server down. midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); } });In the above example, mock server will automatically look for a file default.{some_extension} at ./mocked-data/get/fromFile/GET/default.{some_extension}How File Path Is Calculated For respondWithFile Utility?The path to the mocked data file is auto-calculated based on the route path. For example if the route path is /get/cart than for the default variant, mock server will look for the default.{some_extension} file at ./mocked-data/get/fromFile/GET/default.{some_extension}. For variants, the name of the file should be changed from default to the variant name as shown below:midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }}).variant({ id: 'textData', label: 'Text Data', handler: function (req, reply) { midway.util.respondWithFile(this, reply); }});In above example mock server will look for ./resources/mocked-data/get/fromFile/GET/textData.{some_extension} file for the variant textDataCan I Provide A Custom File Location respondWithFile Utility?Yes. By adding filePath parameter as shown in below example:midway.route({ id: 'CustomResponseFile', label: 'Response From Custom Path', path: '/get/customFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {filePath: './custom.json'}); }});In above example mock server will look for the file under MockedDirectory only but at ./mocked-data/custom.jsonHow To Respond Only With Code?midway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { reply().code(400); }});Can I Return A Response Code With respondWithFile Utility?Yes - by adding code parameter as shown in below example:midway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400}); }});What Is MockedDirectory Path?Mocked directory path is the location to the base directory where all your mocked response file will be stored. This parameter is defined in run-mock-server-console.js file. It is defined at the start of mock server as shown in the code below:require('./endpoints');require('testarmada-midway').start({ host: \"localhost\", mockedDirectory: \"./resources/mocked-data\", port: 8000, project: 'HelloMidway'});Location For Response File For RespondWithFile?If you have set your default folder to be mocked-data, then based on your URL path:For default variant, mock server will look for ./mocked-data/product/grouping/api/collection/GET/default.json and for mixItem variant mock server will look for ./mocked-data/product/grouping/api/collection/GET/mixItem.jsonWhat Are Variants?Variants allows to return a different data set for a given mocked route. Variants can be selected either in the admin UI or through automation APIs to determine what type of response a route should have. Routes are defined using the variant method on the Route object (returned by calling the route method). An object parameter is provided with the following attributes id: the variant id - used for the RESTful admin API and profile settings label: (optional) the variant label - used for display on the admin panel handler: (optional) the HAPI route handler which provides the route responseVariants are useful because they allow you to test multiple scenarios that can happen with your route. Say, for example, you have a route exposing the ability to update a password. You might have several exceptional scenarios that you would want to test out (each could be a variant that you simply select to tell the route handler to use the appropriate response) the password was reset successfully the password didn’t pass validation the old password wasn’t entered correctly the username doesn’t exist and so on…How To Add A Variant To A Route?To add a one or more variants do the following:midway.route({ id: 'message', label: 'Message', path: '/get/message', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { reply('Hello'); }}) .variant({ id: 'hello', label: 'Hello World', handler: function (req, reply) { reply('Hello World'); } }).variant({ id: 'hello', label: 'Hello Universe', handler: function (req, reply) { reply('Hello Universe'); } }); How To Switch Variants In Test Case?browser.setMockVariant({ fixture: \"fixture id\", variant: \"variant id\" }); How To Switch Variants With HTTP Call?You can also switch the variants via HTTP call (Recommended only when not using Midway as a library). As an example, if you want to set variant to helloUniverse for the route below: midway.route({ id: 'helloWorld', label: 'Hello World', path: '/helloWorld', method: 'GET', handler: function (req, reply) { reply('Hello World'); } }) .variant({ id: 'helloUniverse', label: 'Hello Universe', handler: function (req, reply) { reply('Hello Universe'); } });curl -H \"Content-type: application/json\" -X POST -d '{\"variant\":\"<variant>\"}' <host>:<port>/midway/api/route/<routeId>So for the above route, you can switch the variant to helloUniverse like this:curl -H \"Content-type: application/json\" -X POST -d '{\"variant\":\"helloUniverse\"}' http://localhost:8000/midway/api/route/helloWorldWhen using parallel sessions, if you want to switch a variant for a route for a particular session, register the session with mock server like this:curl <host>:<port>/midway/api/registerSession// e.g curl http://localhost:8000/midway/api/registerSessionIf sessions are available, mock server will return a response like: {\"session\":\"33b08d\"}Extract the session id from response and append it to the route id you want to switch variant for e.g:curl -H \"Content-type: application/json\" -X POST -d \"variant\":\"helloUniverse\"}' http://localhost:8000/midway/api/route/helloWorld-33b08dWhat Is Mock Server UI Used For?UI can be used to view and test mocked routes as well as for manual switching of variants when running tests manually.What Is Parallel Sessions?Parallel sessions allows you to run multiple instance of server virtually while running only one server. This is helpful when you are running multiple test cases which access the same routes but different variants as parallel sessions allow you to set different variants on same routes without conflicting. This saves CPU and RAM both as only one server is running instead of multiple. Please see the call flow explaination without and with Parallel Sessions Below:Call Flow Without Parallel SessionsCall Flow With Parallel SessionsHow Can I Enable Parallel Sessions On Mock Server?Add sessions parameter with number of virtual services you want as shown in below example while startung mock Server.require('./endpoints');var midway = require('testarmada-midway');midway.start({ host: \"localhost\", mockedDirectory: \"./resources/mocked-data\", port: 8000, sessions: 2, project: 'HelloMidway'});How Can I Register a Session For Parallel Sessions?var sessionId = midway.registerSession();How Can I Close A Session For Parallel Sessions?var closeSession = midway.closeSession(sessionId);Does Mock Server Has Any Utility To Modify JSON Data Stored In Files?Yes - Mock Server exposes transpose option that cna be passed in respondWithFile method to modify the JSON files dynamically.How Does transposeData Work To Modify JSON Data Stored In Files?If you have many variants for a Rest end point and the mocked data for all variants can use the same JSON response with few changes to the values, than this feature is what you need. This feature allows you to dynamically change a JSON file before sending the response back from the mock server for the request. It removes the need of having one to one mapping of static JSON files with each variants.// Static Response JSON File{ id: \"1234\", name: \"toothpaste\" details: [ { flavor: \"Mint 1\", Size: \"10\", Size_Type: ounce }, { flavor: \"Mint\", Size: \"10\", Size_Type: ounce } ]}// Sample code for substituting id from 1234 to 7777 and flavor from Mint to Mint 2 for second array element in routesmidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { var dataToChange = { 'id': '7777', 'details[1].flavor': 'Mint 2' } midway.util.respondWithFile(this, reply, {transpose: dataToChange}); }});// Dynamic Response JSON File returned from Mock service{ id: \"7777\", name: \"toothpaste\" details: [ { flavor: \"Mint 1\", Size: \"10\", Size_Type: ounce }, { flavor: \"Mint 2\", Size: \"10\", Size_Type: ounce } ]}Can I Use transposeData Functionality Outside Of respondWithFile?Yes - You can use it by Midway Utils.var fileLocation = require(\"path\").join(__dirname, './resources/test-data/data-transposition-test.json');var dataSet = utils.readJsonFile(fileLocation);var dataToChange = { 'items.item[0].id': 1234, // substitue id 0001 to 1234 'items.item[0].val': \"value\", // Add 'val' to first array element of items.item 'items.item[1].id': 4567, // Add 'id' to second array element of items.item 'items.item[0].batters.batter[0].id': 5678 // substitue id 1001 to 5678}substitutedData = midway.util.transposeData(dataSet, dataToChange);// Base JSON file - data-transposition-test.json{ \"items\": { \"item\": [ { \"id\": \"0001\", \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"batters\": { \"type\" : 1, \"batter\": [ { \"id\": \"1001\", \"type\": \"Regular\" }, ] }, \"topping\": [ { \"id\": \"5001\", \"type\": \"None\" } ] } ] }};// Resulted JSON{ \"items\": { \"item\": [ { \"id\": 1234, \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"val\": \"value\" \"batters\": { \"type\": 1, \"batter\": [ {\"id\": 5678, \"type\": \"Regular\"} ] }, \"topping\": [ {\"id\": \"5001\", \"type\": \"None\"} ] }, { \"id\": 4567 } ] }};Why Mock Server Returns Error 415 Unsupported Media Type?If you’re using content type like application/graphql, follow this example midway.route({ id: 'id', label: 'id', path: '/graphql', method: ['POST', 'PUT'], config : { payload: { parse: false, allow: 'application/graphql' } }, handler: function (req, reply) { midway.util.respondWithFile(this, reply, {code: 200}); } });For more details, read this",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/FAQ"
},
"documentation-mocking-native-ios-javascript-contribution-guide": {
"title": "Contribution Guide",
"content": "ArchitectureThese are the very high level components of mocking eco-system.The below diagram shows the mocking components in detail.The mocking service uses midway-smocks which provides the stateful HTTP mocking service built on top of HAPI. It allows to add routes and different scenarios for each route.In addition, the mocking service provides certain utilities via midway-util. It also provides logging facility with midway-loggerMock Server Start flowThe mocking service exposes its features via API’s and HTTP end points. Lets take a look at the sequence of events when the mock server is started.In the above diagram, the actor can be the test code which starts mock server or a developer using the mock service for local development / testing. Users can specify what routes to mock by specifying them in endpoints.js Midway’s start() is invoked with options to start the Midway server Midway creates an instance of Hapi server Midway adds the routes for the system API’s it supports Midway gets the plugin from midway-smocks Midway registers the plugin it obtained from the above step Midway starts the server Once the Midway server is started, you can use the Midway API’s via HTTP Calls or libraries [Read API Guide for examples] Parallel vs non-parallel sessionsWithout Parallel sessionsIf we want to run two test cases in parallel, mocking the same route and returning different data, it won’t be possible with running one mock server and sharing across the whole test suite. So we needed to run one mock server and one application server per test case.With Parallel sessionsWith parallel sessions, we can share one application server and mock server for the whole test suite. It allows to mock the same route but different data for different test cases.To use parallel sessions, the mock server is started with pre-defined number of sessions. For each test, the test case needs to register a session with the mock server. The mock server returns a unique session id which is then sent as part of the request to the application server. If the request gets routed to the mock server for a mocked route, the request handler in mock server extracts the session id from the request, and prepends it to the route. For e.g, if the session id is “123”, it is prepended to the route “/api/getCart” and the route becomes “/123/api/getCart”. For another test using session id “456” , the route will become “/456/api/getCart”. This enables the mock server to be able to return two different responses for the same mocked route.Tech stackLanguage : NodejsNode Version: 4+Unit Tests: MochaCode formatting: EslintCode Coverage Report: IstanbulDeployment informationMocking components are released as npm librariesGit repository informationThe source code for all mocking components reside in Github. Midway Midway Util Midway Magellan Nightwatch Midway Logger Midway Smocks Midway SwaggerDevelopment processTo contribute to the mocking fleet, please follow these steps: Fork the repository https://github.com/TestArmada/midway. If your Github username is “abc” for e.g, your forked repository will be https://github.com/abc/midway. Clone this forked repository using git clone https://github.com/<username>/midway.git and make “midway” your working directory. Create a branch on local with git checkout -b <your branch name>. Note The default branch for all projects is development so any branch you create will be off the development branch. Install dependencies using npm install. Make the code changes in the branch you created in step (3) and write / update the unit tests to verify your changes. Run unit tests using npm test. We use eslint to ensure code formatting. This step runs both unit tests as well as verifies code formatting. We use istanbul for code coverage reporting. 95% is the minimum code coverage we expect for all our components. Once you’re ready, submit your pull request from your branch against the development branch of Midway (https://github.com/TestArmada/midway/tree/development). The PR triggers a Travis build which runs the tests in CI environment (same steps as in (5) above). Once the PR is reviewed, a team member merges the PR into the development branch. When the development branch is merged to master, a team member will push a tag to master, a Travis build is triggered and publishes a new version of the package to npm registry. Note: The same steps above are applicable for contributing to any of the mocking components.",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/Contribution Guide"
},
"documentation-mocking-native-ios-javascript-api-guide": {
"title": "API Guide",
"content": " Mocking API’s Start Mock Server - start() Stop Mock Server - stop() Create Mocked Route - route() Create Variant - variant() Set variant - setMockVariant() Add global variants - addGlobalVariant() Respond With File - respondWithFile() Respond with mock variant - respondWithMockVariant() Set Mock Id - setMockId() Get Mock Id - getMockId() Reset Mock Id - resetMockId() Reset url count - resetURLCount() Get url count - getURLCount() Register session - registerSession() Close session - closeSession() Check session - checkSession() Get sessions - getSessions() Clear sessions - clearSessions() Get project name - getProjectName() Get port information - getPortInfo() Add state - addState() Get state - getState() Clear state - clearState() Enable Metrics - enableMetrics() Check if metrics are enabled - isMetricsEnabled() Dynamic transposition of JSON data - transposeData() Kill process - killProcess() Read contents of a file - readFile() Read contents of a file - readFileSynchronously() Read contents of JSON file - readJsonFile() Write to file - writeFile() Delete file - deleteFile() Check if directory exists - checkDirectoryExists() Check if file exists - checkFileExists() Set Log level - setLogLevel() Get Log level - getLogLevel() Reset Log level - resetLogLevel() Mocking API’sStart Mock Server - start()This API allows to start the mock server.midway.start(options, callback);The following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below No callback The first argument to callback function is the server instance if the start is successful, else it is an error. No where options has the following attributes: Attribute Description Required host Hostname for mock server (default: localhost) No port Port for mock server (default: 8080) No httpsPort Https port for mock server No mockedDirectory Path to the mocked data directory (default: resources/mocked-data w.r.t working directory). No sessions Number of parallel sessions to start the mock server with (default: 0) No collectMetrics Enable mock server to collect usage metrics (default: true) No project Name for your project (default: default) No Examplevar midway = require('testarmada-midway');midway.start({ host: 'localhost', port: 12000, httpsPort: 12001, mockedDirectory: '/resources/mockedData', sessions: 3, project: 'My Project'});Stop Mock Server - stop()This API allows to stop the mock server.midway.stop(server, callback);The following attributes are supported: Attribute Description Required server server instance returned by start() method Yes callback The first argument to callback function is an error if an error is encountered in stopping the server, null otherwise No Examplevar midway = require('testarmada-midway');var server = midway.start(options, callback);// do something with mock servermidway.stop(server, function (error) { if (error) { console.log('Unable to stop mock server'); } else { console.log('Mock Server stopped'); }});Create Mocked Route - route()This API allows to create/add required mocked REST endpoints.midway.route(options);The following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below Yes where options has the following attributes: Attribute Description Required id The unique route id for the mock server Yes label The route label used for display on the Midway Admin Panel No path The route path Yes method The HTTP route method (defaults to GET) No handler The HAPI route handler which provides the route response. This is optional because you could use multiple variants to handle the response (See Variants) No Examplevar midway = require('testarmada-midway');midway.route({ id: 'my_route', label: 'My Route', path: '/api/foo', method: 'GET', handler: function(request, reply) { // Add logic for handler reply('Hello'); }});Create Variant - variant()This API allows to create/add variants. Variants are route handlers that you can select manually (via Midway Admin panel) or Rest call or through Node API to select a different dataset for the response for a given route. Variants are defined using the variant() method on the Route object (returned by calling the route method).midway.route(routeOptions).variant(options)The following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below Yes where options has the following attributes: Attribute Description Required id The unique variant id for a given route Yes label The route label used for display on the Admin Panel No handler The HAPI route handler which provides the variant response for the route No Examplevar midway = require('testarmada-midway');midway.route({ id: 'my_route', path: '/api/foo', handler: function(request, reply) { // this is essentially the same as the \"default\" variant reply({firstName: 'John'}); }}).variant({ id: 'Billy', handler: function(request, reply) { reply({firstName: 'Billy'}); }}).variant({ id: 'Clark', handler: function(request, reply) { reply({firstName: 'Billy'}); }});Set variant - setMockVariant()setMockVariant can be used to set a variant to an existing API path.midway.setMockVariant(options, callback) // with Midway libraryor browser.setMockVariant(options, callback) // when using MagellanThe following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below No callback callback function to be called after setMockVariant() Yes where options has the following attributes: Attribute Description Required fixture Id defined in route Yes variant The variant defined in endpoint.js for the fixture you entered Yes portNumber Port number where the mock server is running on No midwaySessionId Midway session id, if using parallel sessions No ExampleIf the routes are defined likevar midway = require('testarmada-midway');midway.route({ id: 'hello', path: '/helloWorld', handler: function(request, reply) { reply('Hello World'); }}).variant({ id: 'universe', handler: function(request, reply) { reply('Hello Universe'); }});For the route and variant defined as above, you can set the variant to universe as follows:// when using Midway librarymidway.setMockVariant({ fixture: 'hello', // same as id in the .route() options variant: 'universe' // same as id in the .variant() options}, function (err) { if (err) { console.log('Error in setting variant:' + err); } else { console.log('Successfully set variant'); }});or // When using Magellanbrowser.setMockVariant({ fixture: \"hello\", variant: \"universe\" });or Alternately, you can also use `curl` call to set a variant with this POST call to `{host}:{port}/midway/api/route/{routeId}`curl -H \"Content-Type: application/json\" -X POST -d '{\"variant\":\"{universe}\"}' http://localhost:8080/midway/api/route/hello?returnConfig=trueYou can confirm if this works by going to Admin panel and see that for helloWorld route, the variant universe will be highlighted. Also, hitting this url http://localhost:8080/helloWorld will reply with Hello Universe.If the variant does not exist on the route, mock server returns with an Internal Server error (HTTP 500).Add global variants - addGlobalVariant()You can also add global variants that will affect all routes. The attributes to the options are same as that of variant().midway.route(routeOptions).addGlobalVariant(options)whereoptions - JSON object with the same attributes as of variant described in this sectionExamplevar midway = require('testarmada-midway');midway.addGlobalVariant({ id: '500', label: '500 error', handler: function(request, reply) { reply({ statusCode: 500, error: 'Internal Server Error' }).code(500); }})Respond With File - respondWithFile()This API allows to respond with static data stored in a file instead of hard coding the response data in the routes definition. Based on the path of the URL that is being mocked, the response file can be dropped in the directory location and the file will be automatically used by Midway for sending the response. It also allows to specify the absolute path of the response files.midway.util.respondWithFile(route, reply, options);The following attributes are supported: Attribute Description Required route Handle to the midway route object Yes reply Handle to the reply object Yes options JSON object with additional options described below No Attribute Description Required code HTTP Status code to reply with No filePath Static file path of the mocked data No delay Delay response time by this value (in milliseconds) No To use this feature, you can call respondWithFile() from inside route configuration as follows:Examplevar midway = require('testarmada-midway');// Automatic reply of the filemidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}' handler: function(req, reply) { midway.util.respondWithFile(this, reply); }}).variant({ id: 'mixItem', label: 'Mix Item' handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 204, filePath: '../mocked-data/fileName.json', delay: 1000}); }})Note the Use of midway.util to access the method respondWithFileRespond with mock variant - respondWithMockVariant()This API allows to respond with a variant on the main route handler. The ‘variant’ passed in MUST be the variant on existing route.midway.util.respondWithMockVariant(route, variant, req, reply)The following attributes are supported: Attribute Description Required route The route object Yes variant Variant on the route Yes request Request object Yes reply Reply object Yes Examplevar midway = require('testarmada-midway');midway.route({ id: 'respondWithVariant', label: 'Respond With Variant', path: '/respondWithVariant', variantLabel: 'Respond With Main Route', handler: function(req, reply) { midway.util.respondWithMockVariant(this, 'variant', req, reply); // make sure that the variant exist in the same route. }}).variant({ id: 'variant', label: 'Respond With Variant Route', handler: function(req, reply) { reply({ 'message': 'I am an example of respond_with_mock_variant instead of response of main route ' }); }});Note the Use of midway.util to access the method respondWithMockVariantSet Mock Id - setMockId()This API allows to set mock id for a given test case. If this is set, it overrides all the variants and mocked URLs responses to return mocked data from the given directory as mock-id, where mock-id is the directory name.midway.setMockId(mockId, midwaySessionId) // with Midway libraryor browser.setMockId(mocKId, midwaySessionId, callback); // when using MagellanThe following attributes are supported: Attribute Description Required mockId Mock id which is the directory name you want to respond data from Yes midwaySessionId Midway session id, if using parallel sessions No callback callback function to be invoked after mock id is set (only when using Magellan) No The file name should be in the format url-methodName-urlCount.extension for the responses stored under file. For example, for the given route belowvar midway = require('testarmada-midway');midway.route({ id: 'my_route', label: 'My Route', path: '/api/foo', method: 'GET', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }});the file name should be api-foo-GET-1.json for the first time the URL is hit. For second time the URL is hit, the file name returned would be api-foo-GET-2.json. If the specific file for the count is not present, Midway will look for default file api-foo-GET.json, which is also helpful if you want to always return the same response irrespective of the number of times the URL is hit.Example:var midway = require('testarmada-midway');midway.setMockId('cart', 'abcdef'); // All responses should be under \"cart\" directory under your mocked data directoryor browser.setMockId('cart', 'abcdef' , callback);orcurl http://localhost:8000/midway/api/setMockId/cart/abcdefTIP! For a dynamic url such as /app/{cartid}/getStatus the default file name should be app-cartid-getStatus-GET.json and the count specific file name should be like app-cartid-getStatus-GET-1.json.Get Mock Id - getMockId()This API is used to retrieve the currently set mock id.midway.getMockId(midwaySessionId);The following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No Example:var midway = require('testarmada-midway');var mockId = midway.getMockId('abcdef');or curl http://localhost:8000/midway/api/getMockId/cart/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Reset Mock Id - resetMockId()This API is used to reset currently set mock id.midway.resetMockId(midwaySessionId) // with Midway libraryor browser.resetMockId(midwaySessionId, callback); // when using MagellanThe following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No callback callback function to be invoked after mock id is set (only when using Magellan) No Example:var midway = require('testarmada-midway');midway.resetMockId('abcdef');or browser.resetMockId('abcdef', callback);or curl http://localhost:8000/midway/api/resetMockId/cart/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Reset url count - resetURLCount()This API is used to reset URL count to zero. This works in conjunction with setMockId function where you want to restart over for the URL count.midway.resetURLCount(midwaySessionId)or browser.resetURLCount(midwaySessionId, callback)The following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No callback callback function to be be invoked after the mock id is reset No Example:var midway = require('testarmada-midway');midway.resetURLCount('abcdef');or browser.resetCount('abcdef', callback); // 'abcdef' is a midway session id in use for the testorcurl http://localhost:8000/midway/api/resetURLCount/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Get url count - getURLCount()This API is used in conjunction with setMockId function where you want to get the URL count for all mocked calls.midway.getURLCount(midwaySessionId)The following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No Example:var midway = require('testarmada-midway');midway.getURLCount('abcdef');or curl http://localhost:8000/midway/api/getURLCount/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Register session - registerSession()This API is used to register a session with Midway for a test case when using parallel sessions. Midway needs to be started with sessions.midway.registerSession(); // with Midway libraryor browser.registerSession(callback); // with browser testsThe following attributes are supported: Attribute Description Required callback callback function to be be invoked after the session is registered. First argument to the callback is an error object, in case of error, null otherwise. The second argument is the registered session id (Only for browser tests) Yes You can use registerSession() to register a session with Midway and can subsequently use that session id for the current test. Midway returns a unique identifier when registering a session.If no session is available to use, Midway returns with the message NOT_AVAILABLE.ExampleIf midway server is started with sessions, for e.g 3 sessions as shown below,var midway = require('testarmada-midway');midway.start({ host: 'localhost', port: 8080, mockedDirectory: 'resources/mockedData', sessions: 3});var midwaySessionId = midway.registerSession();or browser.registerSession(function (err, sessId) { if (err) { return callback(new Error(\"Unable to get the sessionId\")); } self.midwaySessionId = sessId; client.midwaySessionId = sessId; return callback();});orcurl http://localhost:8000/midway/api/registerSessionClose session - closeSession()This API is used to close a session after running a test so it can be made available for subsequent tests.midway.closeSession(midwaySessionId);or browser.closeSession(midwaySessionId, callback);The following attributes are supported: Attribute Description Required midwaySesssionId Midway session id to be closed Yes callback callback function to be be invoked after the session is registered. First argument to the callback is an error object, in case of error, null otherwise (Only when using browser tests) Yes Examplevar midway = require('testarmada-midway');midway.closeSession('abcdef'); // abcdef is a previously registered session with Midwayor client.closeSession('abcdef', function (err) { if (err) { console.error(\"Error in closing session:\"); }});orcurl http://localhost:8000/midway/api/closeSession/abcdefNote that abcdef is a previously registered session with Midway.Check session - checkSession()This API is used to check status of a session id. It returns one of these states AVAILABLE - If the session is available for use IN_USE - If the session is in use DOES_NOT_EXISTS - If the session id passed is invalid or does not existThe following attributes are supported: Attribute Description Required midwaySessionId Midway session id Yes Examplevar midway = require('testarmada-midway');var status = midway.checkSession('abcdef');or curl http://localhost:8000/midway/api/checkSession/abcdefGet sessions - getSessions()This API is used to get sessions informationmidway.getSessions();Examplevar midway = require('testarmada-midway');var status = midway.getSessions();or curl http://localhost:8000/midway/api/getSessionsClear sessions - clearSessions()This API is used to clear the sessions information.midway.clearSessions();Examplevar midway = require('testarmada-midway');var status = midway.clearSessions();Get project name - getProjectName()This API is used to get the project name passed in Midway optionsmidway.getProjectName();Examplevar midway = require('testarmada-midway');var projectName = midway.getProjectName();Get port information - getPortInfo()This API is used to get the port information passed in Midway optionsmidway.getPortInfo();Examplevar midway = require('testarmada-midway');var portInfo = midway.getPortInfo();Add state - addState()This API is used to add a value to the server state.midway.addState(route, key, value);The following attributes are supported: Attribute Description Required route Route object Yes key Key for the state variable Yes value Value of the state variable Yes Examplevar midway = require('testarmada-midway');midway.route({ id: 'setState', label: 'Add State', path: '/login', handler: function (req, reply) { midway.addState(this, 'loggedIn', true); reply().code(204); }});Get state - getState()This API is used to read a value from the server state.midway.getState(route, key);The following attributes are supported: Attribute Description Required route Route object Yes key Key for the state variable Yes Examplevar midway = require('testarmada-midway');midway.route({ id: 'getState', label: 'Get State', path: '/isLogin', handler: function (req, reply) { var isLoggedIn = midway.getState(this, 'login'); reply(isLoggedIn); }});Clear state - clearState()This API is used to clear a state for a given session id (Defaults to default session).midway.clearState(midwaySessionId);The following attributes are supported: Attribute Description Required midwaySessionId Midway session id No Examplevar midway = require('testarmada-midway');midway.clearState(); // Clears state for default sessionmidway.clearState('abcdef') // Clears state for session id `abcdef`Enable Metrics - enableMetrics()This API is used to enable gathering of usage metrics.midway.enableMetrics(boolean);The following attributes are supported: Attribute Description Required boolean true to enable, false to disable No Examplevar midway = require('testarmada-midway');midway.enableMetrics(true); // Enables gathering of usage metricsmidway.enableMetrics(false); // Disables gathering of usage metricsCheck if metrics are enabled - isMetricsEnabled()This API is used to check if metrics gathering is enabled on Midway. Returns true if metrics gathering is enabled, false otherwisemidway.isMetricsEnabled();Examplevar midway = require('testarmada-midway');midway.isMetricsEnabled();Dynamic transposition of JSON data - transposeData()This API allows to dynamically transpose the JSON datamidway.util.transposeData(dataSet, dataToChange);The following attributes are supported: Attribute Description Required dataSet The data set which needs to change Yes dataToChange The changes needed in the data set Yes To change the JSON data on fly (edit existing values or add values).// Base JSON file{ \"items\": { \"item\": [ { \"id\": \"0001\", \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"batters\": { \"type\" : 1, \"batter\": [ { \"id\": \"1001\", \"type\": \"Regular\" }, ] }, \"topping\": [ { \"id\": \"5001\", \"type\": \"None\" } ] } ] }}// Code examplevar dataToChange = { 'items.item[0].id': 1234, // substitue id 0001 to 1234 'items.item[0].val': \"value\", // Add 'val' to first array element of items.item 'items.item[1].id': 4567, // Add 'id' to second array element of items.item 'items.item[0].batters.batter[0].id': 5678 // substitue id 1001 to 5678}// when using utils classvar fileLocation = require(\"path\").join(__dirname, './resources/test-data/data-transposition-test.json');var dataSet = utils.readJsonFile(fileLocation);substitutedData = midway.util.transposeData(dataSet, dataToChange);// When using with respondwithFile (This will read the file based on url path and transpose the data)midway.util.respondWithFile(this, reply, {transpose: dataToChange});// Resulted JSON{ \"items\": { \"item\": [ { \"id\": 1234, \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"val\": \"value\" \"batters\": { \"type\": 1, \"batter\": [ {\"id\": 5678, \"type\": \"Regular\"} ] }, \"topping\": [ {\"id\": \"5001\", \"type\": \"None\"} ] }, { \"id\": 4567 } ] }}Note the Use of midway.util to access the method transposeDataKill process - killProcess()This API allows to Kill a process with a pidmidway.util.killProcess(pid, signal, callback);The following attributes are supported: Attribute Description Required pid process id to kill Yes signal Signal to send (defaults to SIGKILL if passed undefined) Yes callback Callback function after killprocess completes No Examplevar midway = require('testarmada-midway');midway.util.killProcess(18222, 'SIGKILL', function () { console.log('Process killed);});Note the Use of midway.util to access the method killProcessRead contents of a file - readFile()This API allows to read contents of a file asynchronouslymidway.util.readFile(filePath, callback);The following attributes are supported: Attribute Description Required file path Absolute or relative location of file Yes callback Callback function after file is read. If file is read successfully, the second argument is the file data. In case of error, the first argument is an error. Returns promise if callback is omitted No Examplevar midway = require('testarmada-midway');midway.util.readFile('data.json', function (err, fileData) { if (err) { console.log('Error in reading file ', err); } else { console.log(fileData); }});Note the Use of midway.util to access the method readFileRead contents of a file - readFileSynchronously()This API allows to read contents of a file synchronouslymidway.util.readFileSynchronously(filePath);The following attributes are supported: Attribute Description Required file path Absolute or relative location of file Yes Examplevar midway = require('testarmada-midway');midway.util.readFileSynchronously('data.json');Note the Use of midway.util to access the method readFileSynchronouslyRead contents of JSON file - readJsonFile()This API allows to read contents of a JSON file synchronouslymidway.util.readJsonFile(filePath);The following attributes are supported: Attribute Description Required file path Absolute or relative location of JSON file Yes Examplevar midway = require('testarmada-midway');midway.util.readJsonFile('data.json');Note the Use of midway.util to access the method readJsonFileWrite to file - writeFile()This API allows to write file contents to a filemidway.util.writeFile(filePath, file data, callback);The following attributes are supported: Attribute Description Required file path Absolute or relative location of file Yes file data contents to write Yes callback Callback function after writeFile completes Yes Examplevar midway = require('testarmada-midway');midway.util.writeFile('hello.txt', 'hello world blah blah', function () { console.log('Wrote to file successfully');});Note the Use of midway.util to access the method writeFileDelete file - deleteFile()This API allows to write file contents to a filemidway.util.deleteFile(filePath, callback);The following attributes are supported: Attribute Description Required file location Absolute or relative location of file to delete Yes callback Callback function after deleteFile completes Yes Examplevar midway = require('testarmada-midway');midway.util.deleteFile('filetoDelete.txt', function (err) { if (err) { console.log('Error in deleting file'); }});Note the Use of midway.util to access the method deleteFileCheck if directory exists - checkDirectoryExists()This API allows to check if a directory exists. Returns true if directory exists, false otherwise.midway.util.checkDirectoryExists(directoryPath);The following attributes are supported: Attribute Description Required directory path Location of directory to check Yes Examplevar midway = require('testarmada-midway');midway.util.checkDirectoryExists('/home/data');Note the Use of midway.util to access the method checkDirectoryExistsCheck if file exists - checkFileExists()This API allows to check if a file exists. Returns true if file exists, false otherwise.midway.util.checkFileExists(filePath);The following attributes are supported: Attribute Description Required file path Location of file to check Yes Examplevar midway = require('testarmada-midway');midway.util.checkFileExists('/home/data');Note the Use of midway.util to access the method checkFileExistsSet Log level - setLogLevel()This API allows to set log level on Midwaymidway.log.setLogLevel(logLevel); // when using MidwayorLogger.setLogLevel(logLevel); // when using Midway-LoggerThe following attributes are supported: Attribute Description Required logLevel Log level you want to set .Valid values (warn/info/debug/error) Yes Examplevar midway = require('testarmada-midway');midway.log.setLogLevel('debug');orcurl -X GET http://localhost:8080/midway/api/setloglevel/debugGet Log level - getLogLevel()This API allows to get the current log level on Midwaymidway.log.getLogLevel(); // when using Midwayor Logger.getLogLevel(); // when using Midway-LoggerExamplevar midway = require('testarmada-midway');midway.log.getLogLevel();orvar Logger = require('testarmada-midway'-logger');Logger.getLogLevel();orcurl -X GET http://localhost:8080/midway/api/getloglevelReset Log level - resetLogLevel()This API allows to reset the log level of Midway to info (Default log level)midway.log.resetLogLevel();or Logger.resetLogLevel();Examplevar midway = require('testarmada-midway');midway.log.resetLogLevel();orvar Logger = require('testarmada-midway'-logger');Logger.resetLogLevel();or curl -X GET http://localhost:8080/midway/api/resetloglevel",
"url": "/documentation/Mocking/Native iOS/JAVASCRIPT/API Guide"
},
"documentation-mocking-native-android-javascript-training-guide": {
"title": "Training Guide",
"content": "120 minMocking 101Covered topicsUnderstand of mocking solution and it's featuresHow to set up and start mock serverBasic usage of mocking solution's functionalitiesStart120 minMocking 201Covered topicsLearn creating dynamic URLsRead various REST call request informationCustomize mocked responseStart120 minMocking 301Covered topicsReturning responseSetMockId and APIs for itParallel SessionsStart120 minMocking 401Covered topicsMaintain states in mock serverMocking utility methodsSupported Rest APIs for mock serverStart",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Training Guide/"
},
"documentation-mocking-native-android-javascript-introduction": {
"title": "Introduction",
"content": "Why Use Mock Server?Most of the applications rely on one or many back end services. For successful test execution and fast development, all the dependent backend services should be reliable 100% of the time. However that is not possible as the backend services may be down from time to time for various reasons or may have data inconsistency issues which makes testing/development against live services inefficient and time consuming.To overcome above mentioned limitations, our mocking solution can be used to quickly stub the API responses that are used by your application.We provide a mocking solution which can be leveraged to quickly stub the REST API responses that are used by your application during development or testing. The application points to the mock service host address instead of the live service. Pre-recorded responses are then returned for various endpoints from the mock service. Since there is minimal logic when writing mock service, maintenance and development cost for mock service is minimal. Some of the major development pain-points addressed by the mocking solution are: Unstable services - Teams have saved upto 12 hours/week of development as well as testing time due to downtime / instability of external services. Inconsistent Data - Teams have reduced the test data setup time by about 27 hours/week by eliminating the dependency on external teams for test data setup. Test flakiness - Teams have reduced test flakiness by about 25% Test against negative or unreal scenarios - Teams have reported to have increase test coverage for negative scenarios from no tests before to upto 15 test cases now by simulating service faults deterministicallySome of the key features of the mocking solution are: Ease of setup - Very easy to setup mocked data and use it while development or testing your application Drop and Respond - Respond with a JSON file based on the url route path automatically by dropping JSON response file in folder mapping to url path Test Reuse - ability to execute test cases against mock or live serviceThe mocking solution helps the teams develop and test their web and mobile applications in local as well as CI environments.Feature list Ease of setup - Very easy to setup mocked data and use it while development or testing your application Test Reuse: Execute same test cases against mock or live service. Drop-And-Respond: Respond with a JSON file based on the url route path automatically by dropping json response file in folder mapping to url path. Test De-coupling: No coupling with test cases - Test cases are independent of mock implementation except that setting the desired response for the mock service (which has no impact if the test case is run against a live service). Respond with mocked data from a directory: Mocked data response from specific directory irrespective of Rest APIs Common Utilities: Common utility methods are provided as part of the mocking service which allows quicker test development. UI Interface: Mock service UI for manual testing/debugging. HTTPS Support: HTTPS support for all the urls. Parallel Sessions: Support for single instance mock server for parallel processes Shared Mock data: Allows fetching of mocked data and routes from multiple Git repositories Magellan/Nightwatch integration: Ability to use mocking service with Magellan tests Dynamic Transposition of Mock Data (JSON): Ability to modify response on the fly Support for all file types: Auto evaluation of response file extension and mime type Swagger integration: Automatic mock creator for web-services with swagger definition Platform independent mocks: Mock any service irrespective of the language it is written in Server states: Ability to mock server state Support for Mobile applications: Ability to mock services for mobile applications Manual tests against mock service: Ability to run tests manually against mock servicePlanned features Ability to specify various data storage for mock data Auto-refresh of data Network and Test APIs to support instrumentation Debugging tool to help development by supporting auto-replay of data Support to auto-generate endpoint URLs for mocking Support for changing mocked data via UI",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Introduction"
},
"documentation-mocking-native-android-javascript-getting-started": {
"title": "Getting Started",
"content": "Pre-Requisite Please install the latest Node.jsSetting Mock ServerTo set up mock server, you need only three things: Install mock-server module. Routes for mock-server. Script to start mock-server.Follow the steps below to set-up mock server: Create a new directory mock-server. Create a new file package.json under mock-server directory. Add Mock Server module dependency in package.json as shown below. { \"name\": \"test-midway\", \"dependencies\": { \"testarmada-midway\": \"^1.0.1\" }, \"scripts\": { \"start-mock\": \"node mocks/run-mock-server-console.js\" } } Create another directory mocks under the mock-server directory. Under the directory mocks, create a file endpoints.js with the following code - This file will contain the routes that you want to mock var midway = require('testarmada-midway'); // Required midway.id('example'); // Required // add a route that returns a message \"hello world\" midway.route({ id: 'message', label: 'hello message', path: '/message', method: 'GET', variantLabel: 'hello world', handler: function(req, reply) { reply({message: 'hello world'}); } }); Under the directory mocks, create a file run-mock-server-console.jswith the following code - This file will contain the start-up script for mock server // load mocked endpoint require('./endpoints'); var midway = require('testarmada-midway'); midway.start({ host: 'localhost', mockedDirectory: './mocks', // this can be provided as an absolute path as well. port: 8080, project: 'HelloMidway', //Replace HelloMidway with your project name (without dashes). }); Now open terminal/cmd prompt and navigate to the directory mock-server and run the following command to install Mock Server and dependencies: npm install Starting Mock Server To start mock-server use the following command and than go to http://localhost:8080/midway for mock-server admin-ui. npm run start-mock Common Use Cases Starting mock server on HTTPS port - To enable https, add httpsPort with the desired port number in server start script as shown below: midway.start({ port: 8080, httpsPort: 4444, host: 'localhost', mockedDirectory: './test/resources/mocked-data', project: 'HelloMidway' }); Mocking different REST methods - To mock different rest methods, change the method value in the midway.route() object to any one of the following desired values: POST GET PUT DELETE OPTIONS PATCH Returning different data set for the same mocked route (Variants) - Variants allows to return a different set of data for the same mocked route. To add one or more variants, attach the variant object to midway.route() as shown below: midway.route({ id: 'message', label: 'Hello message', path: '/message', method: 'GET', variantLabel: 'hello world', handler: function (req, reply) { reply({message:'Hello World'}) } }) .variant({ id: 'universe', label: 'hello universe', handler: function (req, reply) { reply({message:'hello universe'}) } }) .variant({ id: 'universe', label: 'hello galaxy', handler: function (req, reply) { reply({message:'Hello Galaxy'}) } }); To get a different set of response, go to admin-ui and select a different variant for the above route and hit http://localhost:8080/message on your favorite browser. Storing mocked response in a file - This feature allows you to respond with a static data stored in a file instead of hard coding the response data in the routes definition. // Automatic reply of the file midway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/test', method: 'GET', variantLabel: 'test-1', handler: function(req, reply) { midway.util.respondWithFile(this, reply); } }) .variant({ id: 'universe', label: 'test-2', handler: function (req, reply) { midway.util.respondWithFile(this, reply); } }); In the above setup, file needed for default route handler (test-1) should be located at (file location/name is based on mockedDirectory/route/method/[default|variant_name].{ext}) ./mocks/product/grouping/api/collection/GET/default.{ext} If this would be a POST call than the file should have been at ./mocks/product/grouping/api/collection/POST/default.{ext} The file name for variants should change from default.{ext} to universe.{ext} in above example that is the file name should be the variant name. Directing Traffic To Mock ServerTo mock live services, your application should allow to configure it to be directed to a mock service instead of live services as shown below:Please update your app server or application by changing the host name of your live service with the host name for your mock server.Mock Server Set-up Flow Identify REST endpoints that needs to be mocked. Gather mocked data for those REST endpoints. Create Mocked Routes by adding them in endpoints.js file. Start Mock Server. Start Your Application server that points to the Mock Server host name instead of live-service. Run your application and the mocked data will be returned for mocked routes.",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Getting Started"
},
"documentation-mocking-native-android-javascript-faq": {
"title": "FAQ",
"content": "What Can Be Mocked?Any Restful service API can be mocked such as: GET POST PUT DELETE OPTIONS and so on..Can AJAX Calls Be Mocked?Yes - It is same as for any other backend service. For AJAX call, point it to the mocked server instance instead of the actual back end service and add a mocked route in the file containing mocked routes for mock server.What Are The Pre-Requisites? node.js 4+ (npm is included in the package)How Can I Add Mock Server Dependency To My Node Project?\"dependencies\": { \"testarmada-midway\": \"1.0.1\" // add the latest version}How To Add A Mocked Route?Add the following code in your routes file, typically endpoints.jsmidway.route({ id: 'helloWorld', // required label: 'Hello World', // Used for Mock Server UI path: '/helloWorld', // the path you want to mock method: 'GET', // The Rest Method you want to mock for this API handler: function (req, reply) { // Add Logic to massage data before returning back to the request. reply('Hello World'); }});How To Create Dynamic URLs?By adding the URL part in curly brackets that you would liek to by dynamic such as /get/customerInfo/{customerid}/{zipcode}For example:midway.route({ id: 'customerInfo', label: 'Customer Info', path: '/get/customerInfo/{customerid}/{zipcode}', // both customerid and zipcode will be dynamic method: 'GET', variantLabel: 'Get Customer Info', handler: function (req, reply) { reply('How to read the customer id :('); }});How To Read Dynamic URLs In Request?var midway = require('testarmada-midway');midway.route({ path: '/get/customerInfo/{customerid}/{zipcode}' handler: function(request, reply) { var params = request.params; var customerid = params.customerid; // customerid is 123 if request is \"/get/customerInfo/123/92127\" var zipcode = params.zipcode; // zipcode is 92127 if request is \"/get/customerInfo/123/92127\" }}); How To Read Header Parameters In Request?var midway = require('testarmada-midway');midway.route({ path: '/api/getCart' handler: function(request, reply) { var headers = request.raw.req.headers; var authorization = headers.authorization; }}); How To Read Payload In Request?var midway = require('testarmada-midway');midway.route({ path: '/api/getCart' handler: function(request, reply) { var payload = request.payload; // foo would be \"bar\" if the posted body content (as JSON) is {\"foo\": \"bar\"} var foo = payload.foo; }}); How To Read Query Parameters In Request?var midway = require('testarmada-midway');midway.route({ path: '/api/getCart' handler: function(request, reply) { var queryParams = request.query; // foo would be \"bar\" if incoming request is \"/api/getCart?foo=bar\" var foo = queryParams.foo; }}); How To Set Custom Headers In Mocked Response?Preferred Waymidway.route({ id: 'header', label: 'Test Headers', path: '/api/testHeaders', handler: function (req, reply) { var myHeaders = { header1: 'test1', header2: 'test2', header3: true }; midway.util.respondWithFile(this, reply, {headers: myHeaders}); }});Alternate Waymidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { reply({message: 'test'}) .header('X-Res-Header', 'I\\'m a custom response header') }});How To Set Custom Cookies In Mocked Response?Preferred Waymidway.route({ id: 'cookie', label: 'Test Cookies', path: '/api/testCookies', handler: function (req, reply) { var cookies = [ {name: 'com.wm.customer', value: 'vz7.0b5c56'}, {name: 'CID', value: 'SmockedCID', options: {domain: 'domain', path: '/'}}, {name: 'anotherCookie', value: 'cookieValue'} ]; midway.util.respondWithFile(this, reply, {cookies: cookies}); }});Alternate Waymidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { reply({message: 'test'}) .state('test-cookie', 'I\\'m a custom response cookie') }}); How To Set CORS Headers?var corsHeaders = { origin: ['*'], headers: [\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept\"], credentials: true,}// Itemsmidway.route({ id: 'tempo', label: 'Tempo', path: '/tempo1', config: { cors: corsHeaders }, handler: function(req, reply) { midway.util.respondWithFile(this, reply); }});What Is respondWithFile Utility?This feature allows you to respond with a data stored in a file instead of hard coding the response data in the routes definition. This way user does not have to hard-code/change the response in handler and rather can just swap the file with different data without even bringing the server down. midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); } });In the above example, mock server will automatically look for a file default.{some_extension} at ./mocked-data/get/fromFile/GET/default.{some_extension}How File Path Is Calculated For respondWithFile Utility?The path to the mocked data file is auto-calculated based on the route path. For example if the route path is /get/cart than for the default variant, mock server will look for the default.{some_extension} file at ./mocked-data/get/fromFile/GET/default.{some_extension}. For variants, the name of the file should be changed from default to the variant name as shown below:midway.route({ id: 'ResponseFromFile', label: 'Response From File', path: '/get/fromFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }}).variant({ id: 'textData', label: 'Text Data', handler: function (req, reply) { midway.util.respondWithFile(this, reply); }});In above example mock server will look for ./resources/mocked-data/get/fromFile/GET/textData.{some_extension} file for the variant textDataCan I Provide A Custom File Location respondWithFile Utility?Yes. By adding filePath parameter as shown in below example:midway.route({ id: 'CustomResponseFile', label: 'Response From Custom Path', path: '/get/customFile', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {filePath: './custom.json'}); }});In above example mock server will look for the file under MockedDirectory only but at ./mocked-data/custom.jsonHow To Respond Only With Code?midway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { reply().code(400); }});Can I Return A Response Code With respondWithFile Utility?Yes - by adding code parameter as shown in below example:midway.route({ id: 'message', label: 'hello message', path: '/message', handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 400}); }});What Is MockedDirectory Path?Mocked directory path is the location to the base directory where all your mocked response file will be stored. This parameter is defined in run-mock-server-console.js file. It is defined at the start of mock server as shown in the code below:require('./endpoints');require('testarmada-midway').start({ host: \"localhost\", mockedDirectory: \"./resources/mocked-data\", port: 8000, project: 'HelloMidway'});Location For Response File For RespondWithFile?If you have set your default folder to be mocked-data, then based on your URL path:For default variant, mock server will look for ./mocked-data/product/grouping/api/collection/GET/default.json and for mixItem variant mock server will look for ./mocked-data/product/grouping/api/collection/GET/mixItem.jsonWhat Are Variants?Variants allows to return a different data set for a given mocked route. Variants can be selected either in the admin UI or through automation APIs to determine what type of response a route should have. Routes are defined using the variant method on the Route object (returned by calling the route method). An object parameter is provided with the following attributes id: the variant id - used for the RESTful admin API and profile settings label: (optional) the variant label - used for display on the admin panel handler: (optional) the HAPI route handler which provides the route responseVariants are useful because they allow you to test multiple scenarios that can happen with your route. Say, for example, you have a route exposing the ability to update a password. You might have several exceptional scenarios that you would want to test out (each could be a variant that you simply select to tell the route handler to use the appropriate response) the password was reset successfully the password didn’t pass validation the old password wasn’t entered correctly the username doesn’t exist and so on…How To Add A Variant To A Route?To add a one or more variants do the following:midway.route({ id: 'message', label: 'Message', path: '/get/message', method: 'GET', variantLabel: 'Hello', handler: function (req, reply) { reply('Hello'); }}) .variant({ id: 'hello', label: 'Hello World', handler: function (req, reply) { reply('Hello World'); } }).variant({ id: 'hello', label: 'Hello Universe', handler: function (req, reply) { reply('Hello Universe'); } }); How To Switch Variants In Test Case?browser.setMockVariant({ fixture: \"fixture id\", variant: \"variant id\" }); How To Switch Variants With HTTP Call?You can also switch the variants via HTTP call (Recommended only when not using Midway as a library). As an example, if you want to set variant to helloUniverse for the route below: midway.route({ id: 'helloWorld', label: 'Hello World', path: '/helloWorld', method: 'GET', handler: function (req, reply) { reply('Hello World'); } }) .variant({ id: 'helloUniverse', label: 'Hello Universe', handler: function (req, reply) { reply('Hello Universe'); } });curl -H \"Content-type: application/json\" -X POST -d '{\"variant\":\"<variant>\"}' <host>:<port>/midway/api/route/<routeId>So for the above route, you can switch the variant to helloUniverse like this:curl -H \"Content-type: application/json\" -X POST -d '{\"variant\":\"helloUniverse\"}' http://localhost:8000/midway/api/route/helloWorldWhen using parallel sessions, if you want to switch a variant for a route for a particular session, register the session with mock server like this:curl <host>:<port>/midway/api/registerSession// e.g curl http://localhost:8000/midway/api/registerSessionIf sessions are available, mock server will return a response like: {\"session\":\"33b08d\"}Extract the session id from response and append it to the route id you want to switch variant for e.g:curl -H \"Content-type: application/json\" -X POST -d \"variant\":\"helloUniverse\"}' http://localhost:8000/midway/api/route/helloWorld-33b08dWhat Is Mock Server UI Used For?UI can be used to view and test mocked routes as well as for manual switching of variants when running tests manually.What Is Parallel Sessions?Parallel sessions allows you to run multiple instance of server virtually while running only one server. This is helpful when you are running multiple test cases which access the same routes but different variants as parallel sessions allow you to set different variants on same routes without conflicting. This saves CPU and RAM both as only one server is running instead of multiple. Please see the call flow explaination without and with Parallel Sessions Below:Call Flow Without Parallel SessionsCall Flow With Parallel SessionsHow Can I Enable Parallel Sessions On Mock Server?Add sessions parameter with number of virtual services you want as shown in below example while startung mock Server.require('./endpoints');var midway = require('testarmada-midway');midway.start({ host: \"localhost\", mockedDirectory: \"./resources/mocked-data\", port: 8000, sessions: 2, project: 'HelloMidway'});How Can I Register a Session For Parallel Sessions?var sessionId = midway.registerSession();How Can I Close A Session For Parallel Sessions?var closeSession = midway.closeSession(sessionId);Does Mock Server Has Any Utility To Modify JSON Data Stored In Files?Yes - Mock Server exposes transpose option that cna be passed in respondWithFile method to modify the JSON files dynamically.How Does transposeData Work To Modify JSON Data Stored In Files?If you have many variants for a Rest end point and the mocked data for all variants can use the same JSON response with few changes to the values, than this feature is what you need. This feature allows you to dynamically change a JSON file before sending the response back from the mock server for the request. It removes the need of having one to one mapping of static JSON files with each variants.// Static Response JSON File{ id: \"1234\", name: \"toothpaste\" details: [ { flavor: \"Mint 1\", Size: \"10\", Size_Type: ounce }, { flavor: \"Mint\", Size: \"10\", Size_Type: ounce } ]}// Sample code for substituting id from 1234 to 7777 and flavor from Mint to Mint 2 for second array element in routesmidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}', handler: function(req, reply) { var dataToChange = { 'id': '7777', 'details[1].flavor': 'Mint 2' } midway.util.respondWithFile(this, reply, {transpose: dataToChange}); }});// Dynamic Response JSON File returned from Mock service{ id: \"7777\", name: \"toothpaste\" details: [ { flavor: \"Mint 1\", Size: \"10\", Size_Type: ounce }, { flavor: \"Mint 2\", Size: \"10\", Size_Type: ounce } ]}Can I Use transposeData Functionality Outside Of respondWithFile?Yes - You can use it by Midway Utils.var fileLocation = require(\"path\").join(__dirname, './resources/test-data/data-transposition-test.json');var dataSet = utils.readJsonFile(fileLocation);var dataToChange = { 'items.item[0].id': 1234, // substitue id 0001 to 1234 'items.item[0].val': \"value\", // Add 'val' to first array element of items.item 'items.item[1].id': 4567, // Add 'id' to second array element of items.item 'items.item[0].batters.batter[0].id': 5678 // substitue id 1001 to 5678}substitutedData = midway.util.transposeData(dataSet, dataToChange);// Base JSON file - data-transposition-test.json{ \"items\": { \"item\": [ { \"id\": \"0001\", \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"batters\": { \"type\" : 1, \"batter\": [ { \"id\": \"1001\", \"type\": \"Regular\" }, ] }, \"topping\": [ { \"id\": \"5001\", \"type\": \"None\" } ] } ] }};// Resulted JSON{ \"items\": { \"item\": [ { \"id\": 1234, \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"val\": \"value\" \"batters\": { \"type\": 1, \"batter\": [ {\"id\": 5678, \"type\": \"Regular\"} ] }, \"topping\": [ {\"id\": \"5001\", \"type\": \"None\"} ] }, { \"id\": 4567 } ] }};Why Mock Server Returns Error 415 Unsupported Media Type?If you’re using content type like application/graphql, follow this example midway.route({ id: 'id', label: 'id', path: '/graphql', method: ['POST', 'PUT'], config : { payload: { parse: false, allow: 'application/graphql' } }, handler: function (req, reply) { midway.util.respondWithFile(this, reply, {code: 200}); } });For more details, read this",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/FAQ"
},
"documentation-mocking-native-android-javascript-contribution-guide": {
"title": "Contribution Guide",
"content": "ArchitectureThese are the very high level components of mocking eco-system.The below diagram shows the mocking components in detail.The mocking service uses midway-smocks which provides the stateful HTTP mocking service built on top of HAPI. It allows to add routes and different scenarios for each route.In addition, the mocking service provides certain utilities via midway-util. It also provides logging facility with midway-loggerMock Server Start flowThe mocking service exposes its features via API’s and HTTP end points. Lets take a look at the sequence of events when the mock server is started.In the above diagram, the actor can be the test code which starts mock server or a developer using the mock service for local development / testing. Users can specify what routes to mock by specifying them in endpoints.js Midway’s start() is invoked with options to start the Midway server Midway creates an instance of Hapi server Midway adds the routes for the system API’s it supports Midway gets the plugin from midway-smocks Midway registers the plugin it obtained from the above step Midway starts the server Once the Midway server is started, you can use the Midway API’s via HTTP Calls or libraries [Read API Guide for examples] Parallel vs non-parallel sessionsWithout Parallel sessionsIf we want to run two test cases in parallel, mocking the same route and returning different data, it won’t be possible with running one mock server and sharing across the whole test suite. So we needed to run one mock server and one application server per test case.With Parallel sessionsWith parallel sessions, we can share one application server and mock server for the whole test suite. It allows to mock the same route but different data for different test cases.To use parallel sessions, the mock server is started with pre-defined number of sessions. For each test, the test case needs to register a session with the mock server. The mock server returns a unique session id which is then sent as part of the request to the application server. If the request gets routed to the mock server for a mocked route, the request handler in mock server extracts the session id from the request, and prepends it to the route. For e.g, if the session id is “123”, it is prepended to the route “/api/getCart” and the route becomes “/123/api/getCart”. For another test using session id “456” , the route will become “/456/api/getCart”. This enables the mock server to be able to return two different responses for the same mocked route.Tech stackLanguage : NodejsNode Version: 4+Unit Tests: MochaCode formatting: EslintCode Coverage Report: IstanbulDeployment informationMocking components are released as npm librariesGit repository informationThe source code for all mocking components reside in Github. Midway Midway Util Midway Magellan Nightwatch Midway Logger Midway Smocks Midway SwaggerDevelopment processTo contribute to the mocking fleet, please follow these steps: Fork the repository https://github.com/TestArmada/midway. If your Github username is “abc” for e.g, your forked repository will be https://github.com/abc/midway. Clone this forked repository using git clone https://github.com/<username>/midway.git and make “midway” your working directory. Create a branch on local with git checkout -b <your branch name>. Note The default branch for all projects is development so any branch you create will be off the development branch. Install dependencies using npm install. Make the code changes in the branch you created in step (3) and write / update the unit tests to verify your changes. Run unit tests using npm test. We use eslint to ensure code formatting. This step runs both unit tests as well as verifies code formatting. We use istanbul for code coverage reporting. 95% is the minimum code coverage we expect for all our components. Once you’re ready, submit your pull request from your branch against the development branch of Midway (https://github.com/TestArmada/midway/tree/development). The PR triggers a Travis build which runs the tests in CI environment (same steps as in (5) above). Once the PR is reviewed, a team member merges the PR into the development branch. When the development branch is merged to master, a team member will push a tag to master, a Travis build is triggered and publishes a new version of the package to npm registry. Note: The same steps above are applicable for contributing to any of the mocking components.",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/Contribution Guide"
},
"documentation-mocking-native-android-javascript-api-guide": {
"title": "API Guide",
"content": " Mocking API’s Start Mock Server - start() Stop Mock Server - stop() Create Mocked Route - route() Create Variant - variant() Set variant - setMockVariant() Add global variants - addGlobalVariant() Respond With File - respondWithFile() Respond with mock variant - respondWithMockVariant() Set Mock Id - setMockId() Get Mock Id - getMockId() Reset Mock Id - resetMockId() Reset url count - resetURLCount() Get url count - getURLCount() Register session - registerSession() Close session - closeSession() Check session - checkSession() Get sessions - getSessions() Clear sessions - clearSessions() Get project name - getProjectName() Get port information - getPortInfo() Add state - addState() Get state - getState() Clear state - clearState() Enable Metrics - enableMetrics() Check if metrics are enabled - isMetricsEnabled() Dynamic transposition of JSON data - transposeData() Kill process - killProcess() Read contents of a file - readFile() Read contents of a file - readFileSynchronously() Read contents of JSON file - readJsonFile() Write to file - writeFile() Delete file - deleteFile() Check if directory exists - checkDirectoryExists() Check if file exists - checkFileExists() Set Log level - setLogLevel() Get Log level - getLogLevel() Reset Log level - resetLogLevel() Mocking API’sStart Mock Server - start()This API allows to start the mock server.midway.start(options, callback);The following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below No callback The first argument to callback function is the server instance if the start is successful, else it is an error. No where options has the following attributes: Attribute Description Required host Hostname for mock server (default: localhost) No port Port for mock server (default: 8080) No httpsPort Https port for mock server No mockedDirectory Path to the mocked data directory (default: resources/mocked-data w.r.t working directory). No sessions Number of parallel sessions to start the mock server with (default: 0) No collectMetrics Enable mock server to collect usage metrics (default: true) No project Name for your project (default: default) No Examplevar midway = require('testarmada-midway');midway.start({ host: 'localhost', port: 12000, httpsPort: 12001, mockedDirectory: '/resources/mockedData', sessions: 3, project: 'My Project'});Stop Mock Server - stop()This API allows to stop the mock server.midway.stop(server, callback);The following attributes are supported: Attribute Description Required server server instance returned by start() method Yes callback The first argument to callback function is an error if an error is encountered in stopping the server, null otherwise No Examplevar midway = require('testarmada-midway');var server = midway.start(options, callback);// do something with mock servermidway.stop(server, function (error) { if (error) { console.log('Unable to stop mock server'); } else { console.log('Mock Server stopped'); }});Create Mocked Route - route()This API allows to create/add required mocked REST endpoints.midway.route(options);The following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below Yes where options has the following attributes: Attribute Description Required id The unique route id for the mock server Yes label The route label used for display on the Midway Admin Panel No path The route path Yes method The HTTP route method (defaults to GET) No handler The HAPI route handler which provides the route response. This is optional because you could use multiple variants to handle the response (See Variants) No Examplevar midway = require('testarmada-midway');midway.route({ id: 'my_route', label: 'My Route', path: '/api/foo', method: 'GET', handler: function(request, reply) { // Add logic for handler reply('Hello'); }});Create Variant - variant()This API allows to create/add variants. Variants are route handlers that you can select manually (via Midway Admin panel) or Rest call or through Node API to select a different dataset for the response for a given route. Variants are defined using the variant() method on the Route object (returned by calling the route method).midway.route(routeOptions).variant(options)The following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below Yes where options has the following attributes: Attribute Description Required id The unique variant id for a given route Yes label The route label used for display on the Admin Panel No handler The HAPI route handler which provides the variant response for the route No Examplevar midway = require('testarmada-midway');midway.route({ id: 'my_route', path: '/api/foo', handler: function(request, reply) { // this is essentially the same as the \"default\" variant reply({firstName: 'John'}); }}).variant({ id: 'Billy', handler: function(request, reply) { reply({firstName: 'Billy'}); }}).variant({ id: 'Clark', handler: function(request, reply) { reply({firstName: 'Billy'}); }});Set variant - setMockVariant()setMockVariant can be used to set a variant to an existing API path.midway.setMockVariant(options, callback) // with Midway libraryor browser.setMockVariant(options, callback) // when using MagellanThe following attributes are supported: Attribute Description Required options JSON object with the attributes described in the table below No callback callback function to be called after setMockVariant() Yes where options has the following attributes: Attribute Description Required fixture Id defined in route Yes variant The variant defined in endpoint.js for the fixture you entered Yes portNumber Port number where the mock server is running on No midwaySessionId Midway session id, if using parallel sessions No ExampleIf the routes are defined likevar midway = require('testarmada-midway');midway.route({ id: 'hello', path: '/helloWorld', handler: function(request, reply) { reply('Hello World'); }}).variant({ id: 'universe', handler: function(request, reply) { reply('Hello Universe'); }});For the route and variant defined as above, you can set the variant to universe as follows:// when using Midway librarymidway.setMockVariant({ fixture: 'hello', // same as id in the .route() options variant: 'universe' // same as id in the .variant() options}, function (err) { if (err) { console.log('Error in setting variant:' + err); } else { console.log('Successfully set variant'); }});or // When using Magellanbrowser.setMockVariant({ fixture: \"hello\", variant: \"universe\" });or Alternately, you can also use `curl` call to set a variant with this POST call to `{host}:{port}/midway/api/route/{routeId}`curl -H \"Content-Type: application/json\" -X POST -d '{\"variant\":\"{universe}\"}' http://localhost:8080/midway/api/route/hello?returnConfig=trueYou can confirm if this works by going to Admin panel and see that for helloWorld route, the variant universe will be highlighted. Also, hitting this url http://localhost:8080/helloWorld will reply with Hello Universe.If the variant does not exist on the route, mock server returns with an Internal Server error (HTTP 500).Add global variants - addGlobalVariant()You can also add global variants that will affect all routes. The attributes to the options are same as that of variant().midway.route(routeOptions).addGlobalVariant(options)whereoptions - JSON object with the same attributes as of variant described in this sectionExamplevar midway = require('testarmada-midway');midway.addGlobalVariant({ id: '500', label: '500 error', handler: function(request, reply) { reply({ statusCode: 500, error: 'Internal Server Error' }).code(500); }})Respond With File - respondWithFile()This API allows to respond with static data stored in a file instead of hard coding the response data in the routes definition. Based on the path of the URL that is being mocked, the response file can be dropped in the directory location and the file will be automatically used by Midway for sending the response. It also allows to specify the absolute path of the response files.midway.util.respondWithFile(route, reply, options);The following attributes are supported: Attribute Description Required route Handle to the midway route object Yes reply Handle to the reply object Yes options JSON object with additional options described below No Attribute Description Required code HTTP Status code to reply with No filePath Static file path of the mocked data No delay Delay response time by this value (in milliseconds) No To use this feature, you can call respondWithFile() from inside route configuration as follows:Examplevar midway = require('testarmada-midway');// Automatic reply of the filemidway.route({ id: 'Get Collection', label: 'Get Collections', path: '/product/grouping/api/collection/{collectionId}' handler: function(req, reply) { midway.util.respondWithFile(this, reply); }}).variant({ id: 'mixItem', label: 'Mix Item' handler: function(req, reply) { midway.util.respondWithFile(this, reply, {code: 204, filePath: '../mocked-data/fileName.json', delay: 1000}); }})Note the Use of midway.util to access the method respondWithFileRespond with mock variant - respondWithMockVariant()This API allows to respond with a variant on the main route handler. The ‘variant’ passed in MUST be the variant on existing route.midway.util.respondWithMockVariant(route, variant, req, reply)The following attributes are supported: Attribute Description Required route The route object Yes variant Variant on the route Yes request Request object Yes reply Reply object Yes Examplevar midway = require('testarmada-midway');midway.route({ id: 'respondWithVariant', label: 'Respond With Variant', path: '/respondWithVariant', variantLabel: 'Respond With Main Route', handler: function(req, reply) { midway.util.respondWithMockVariant(this, 'variant', req, reply); // make sure that the variant exist in the same route. }}).variant({ id: 'variant', label: 'Respond With Variant Route', handler: function(req, reply) { reply({ 'message': 'I am an example of respond_with_mock_variant instead of response of main route ' }); }});Note the Use of midway.util to access the method respondWithMockVariantSet Mock Id - setMockId()This API allows to set mock id for a given test case. If this is set, it overrides all the variants and mocked URLs responses to return mocked data from the given directory as mock-id, where mock-id is the directory name.midway.setMockId(mockId, midwaySessionId) // with Midway libraryor browser.setMockId(mocKId, midwaySessionId, callback); // when using MagellanThe following attributes are supported: Attribute Description Required mockId Mock id which is the directory name you want to respond data from Yes midwaySessionId Midway session id, if using parallel sessions No callback callback function to be invoked after mock id is set (only when using Magellan) No The file name should be in the format url-methodName-urlCount.extension for the responses stored under file. For example, for the given route belowvar midway = require('testarmada-midway');midway.route({ id: 'my_route', label: 'My Route', path: '/api/foo', method: 'GET', handler: function(req, reply) { midway.util.respondWithFile(this, reply); }});the file name should be api-foo-GET-1.json for the first time the URL is hit. For second time the URL is hit, the file name returned would be api-foo-GET-2.json. If the specific file for the count is not present, Midway will look for default file api-foo-GET.json, which is also helpful if you want to always return the same response irrespective of the number of times the URL is hit.Example:var midway = require('testarmada-midway');midway.setMockId('cart', 'abcdef'); // All responses should be under \"cart\" directory under your mocked data directoryor browser.setMockId('cart', 'abcdef' , callback);orcurl http://localhost:8000/midway/api/setMockId/cart/abcdefTIP! For a dynamic url such as /app/{cartid}/getStatus the default file name should be app-cartid-getStatus-GET.json and the count specific file name should be like app-cartid-getStatus-GET-1.json.Get Mock Id - getMockId()This API is used to retrieve the currently set mock id.midway.getMockId(midwaySessionId);The following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No Example:var midway = require('testarmada-midway');var mockId = midway.getMockId('abcdef');or curl http://localhost:8000/midway/api/getMockId/cart/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Reset Mock Id - resetMockId()This API is used to reset currently set mock id.midway.resetMockId(midwaySessionId) // with Midway libraryor browser.resetMockId(midwaySessionId, callback); // when using MagellanThe following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No callback callback function to be invoked after mock id is set (only when using Magellan) No Example:var midway = require('testarmada-midway');midway.resetMockId('abcdef');or browser.resetMockId('abcdef', callback);or curl http://localhost:8000/midway/api/resetMockId/cart/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Reset url count - resetURLCount()This API is used to reset URL count to zero. This works in conjunction with setMockId function where you want to restart over for the URL count.midway.resetURLCount(midwaySessionId)or browser.resetURLCount(midwaySessionId, callback)The following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No callback callback function to be be invoked after the mock id is reset No Example:var midway = require('testarmada-midway');midway.resetURLCount('abcdef');or browser.resetCount('abcdef', callback); // 'abcdef' is a midway session id in use for the testorcurl http://localhost:8000/midway/api/resetURLCount/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Get url count - getURLCount()This API is used in conjunction with setMockId function where you want to get the URL count for all mocked calls.midway.getURLCount(midwaySessionId)The following attributes are supported: Attribute Description Required midwaySessionId Midway session id, if using parallel sessions No Example:var midway = require('testarmada-midway');midway.getURLCount('abcdef');or curl http://localhost:8000/midway/api/getURLCount/abcdefNote that abcdef is the session id in use for the current test (optional, if not using parallel sessions)Register session - registerSession()This API is used to register a session with Midway for a test case when using parallel sessions. Midway needs to be started with sessions.midway.registerSession(); // with Midway libraryor browser.registerSession(callback); // with browser testsThe following attributes are supported: Attribute Description Required callback callback function to be be invoked after the session is registered. First argument to the callback is an error object, in case of error, null otherwise. The second argument is the registered session id (Only for browser tests) Yes You can use registerSession() to register a session with Midway and can subsequently use that session id for the current test. Midway returns a unique identifier when registering a session.If no session is available to use, Midway returns with the message NOT_AVAILABLE.ExampleIf midway server is started with sessions, for e.g 3 sessions as shown below,var midway = require('testarmada-midway');midway.start({ host: 'localhost', port: 8080, mockedDirectory: 'resources/mockedData', sessions: 3});var midwaySessionId = midway.registerSession();or browser.registerSession(function (err, sessId) { if (err) { return callback(new Error(\"Unable to get the sessionId\")); } self.midwaySessionId = sessId; client.midwaySessionId = sessId; return callback();});orcurl http://localhost:8000/midway/api/registerSessionClose session - closeSession()This API is used to close a session after running a test so it can be made available for subsequent tests.midway.closeSession(midwaySessionId);or browser.closeSession(midwaySessionId, callback);The following attributes are supported: Attribute Description Required midwaySesssionId Midway session id to be closed Yes callback callback function to be be invoked after the session is registered. First argument to the callback is an error object, in case of error, null otherwise (Only when using browser tests) Yes Examplevar midway = require('testarmada-midway');midway.closeSession('abcdef'); // abcdef is a previously registered session with Midwayor client.closeSession('abcdef', function (err) { if (err) { console.error(\"Error in closing session:\"); }});orcurl http://localhost:8000/midway/api/closeSession/abcdefNote that abcdef is a previously registered session with Midway.Check session - checkSession()This API is used to check status of a session id. It returns one of these states AVAILABLE - If the session is available for use IN_USE - If the session is in use DOES_NOT_EXISTS - If the session id passed is invalid or does not existThe following attributes are supported: Attribute Description Required midwaySessionId Midway session id Yes Examplevar midway = require('testarmada-midway');var status = midway.checkSession('abcdef');or curl http://localhost:8000/midway/api/checkSession/abcdefGet sessions - getSessions()This API is used to get sessions informationmidway.getSessions();Examplevar midway = require('testarmada-midway');var status = midway.getSessions();or curl http://localhost:8000/midway/api/getSessionsClear sessions - clearSessions()This API is used to clear the sessions information.midway.clearSessions();Examplevar midway = require('testarmada-midway');var status = midway.clearSessions();Get project name - getProjectName()This API is used to get the project name passed in Midway optionsmidway.getProjectName();Examplevar midway = require('testarmada-midway');var projectName = midway.getProjectName();Get port information - getPortInfo()This API is used to get the port information passed in Midway optionsmidway.getPortInfo();Examplevar midway = require('testarmada-midway');var portInfo = midway.getPortInfo();Add state - addState()This API is used to add a value to the server state.midway.addState(route, key, value);The following attributes are supported: Attribute Description Required route Route object Yes key Key for the state variable Yes value Value of the state variable Yes Examplevar midway = require('testarmada-midway');midway.route({ id: 'setState', label: 'Add State', path: '/login', handler: function (req, reply) { midway.addState(this, 'loggedIn', true); reply().code(204); }});Get state - getState()This API is used to read a value from the server state.midway.getState(route, key);The following attributes are supported: Attribute Description Required route Route object Yes key Key for the state variable Yes Examplevar midway = require('testarmada-midway');midway.route({ id: 'getState', label: 'Get State', path: '/isLogin', handler: function (req, reply) { var isLoggedIn = midway.getState(this, 'login'); reply(isLoggedIn); }});Clear state - clearState()This API is used to clear a state for a given session id (Defaults to default session).midway.clearState(midwaySessionId);The following attributes are supported: Attribute Description Required midwaySessionId Midway session id No Examplevar midway = require('testarmada-midway');midway.clearState(); // Clears state for default sessionmidway.clearState('abcdef') // Clears state for session id `abcdef`Enable Metrics - enableMetrics()This API is used to enable gathering of usage metrics.midway.enableMetrics(boolean);The following attributes are supported: Attribute Description Required boolean true to enable, false to disable No Examplevar midway = require('testarmada-midway');midway.enableMetrics(true); // Enables gathering of usage metricsmidway.enableMetrics(false); // Disables gathering of usage metricsCheck if metrics are enabled - isMetricsEnabled()This API is used to check if metrics gathering is enabled on Midway. Returns true if metrics gathering is enabled, false otherwisemidway.isMetricsEnabled();Examplevar midway = require('testarmada-midway');midway.isMetricsEnabled();Dynamic transposition of JSON data - transposeData()This API allows to dynamically transpose the JSON datamidway.util.transposeData(dataSet, dataToChange);The following attributes are supported: Attribute Description Required dataSet The data set which needs to change Yes dataToChange The changes needed in the data set Yes To change the JSON data on fly (edit existing values or add values).// Base JSON file{ \"items\": { \"item\": [ { \"id\": \"0001\", \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"batters\": { \"type\" : 1, \"batter\": [ { \"id\": \"1001\", \"type\": \"Regular\" }, ] }, \"topping\": [ { \"id\": \"5001\", \"type\": \"None\" } ] } ] }}// Code examplevar dataToChange = { 'items.item[0].id': 1234, // substitue id 0001 to 1234 'items.item[0].val': \"value\", // Add 'val' to first array element of items.item 'items.item[1].id': 4567, // Add 'id' to second array element of items.item 'items.item[0].batters.batter[0].id': 5678 // substitue id 1001 to 5678}// when using utils classvar fileLocation = require(\"path\").join(__dirname, './resources/test-data/data-transposition-test.json');var dataSet = utils.readJsonFile(fileLocation);substitutedData = midway.util.transposeData(dataSet, dataToChange);// When using with respondwithFile (This will read the file based on url path and transpose the data)midway.util.respondWithFile(this, reply, {transpose: dataToChange});// Resulted JSON{ \"items\": { \"item\": [ { \"id\": 1234, \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"val\": \"value\" \"batters\": { \"type\": 1, \"batter\": [ {\"id\": 5678, \"type\": \"Regular\"} ] }, \"topping\": [ {\"id\": \"5001\", \"type\": \"None\"} ] }, { \"id\": 4567 } ] }}Note the Use of midway.util to access the method transposeDataKill process - killProcess()This API allows to Kill a process with a pidmidway.util.killProcess(pid, signal, callback);The following attributes are supported: Attribute Description Required pid process id to kill Yes signal Signal to send (defaults to SIGKILL if passed undefined) Yes callback Callback function after killprocess completes No Examplevar midway = require('testarmada-midway');midway.util.killProcess(18222, 'SIGKILL', function () { console.log('Process killed);});Note the Use of midway.util to access the method killProcessRead contents of a file - readFile()This API allows to read contents of a file asynchronouslymidway.util.readFile(filePath, callback);The following attributes are supported: Attribute Description Required file path Absolute or relative location of file Yes callback Callback function after file is read. If file is read successfully, the second argument is the file data. In case of error, the first argument is an error. Returns promise if callback is omitted No Examplevar midway = require('testarmada-midway');midway.util.readFile('data.json', function (err, fileData) { if (err) { console.log('Error in reading file ', err); } else { console.log(fileData); }});Note the Use of midway.util to access the method readFileRead contents of a file - readFileSynchronously()This API allows to read contents of a file synchronouslymidway.util.readFileSynchronously(filePath);The following attributes are supported: Attribute Description Required file path Absolute or relative location of file Yes Examplevar midway = require('testarmada-midway');midway.util.readFileSynchronously('data.json');Note the Use of midway.util to access the method readFileSynchronouslyRead contents of JSON file - readJsonFile()This API allows to read contents of a JSON file synchronouslymidway.util.readJsonFile(filePath);The following attributes are supported: Attribute Description Required file path Absolute or relative location of JSON file Yes Examplevar midway = require('testarmada-midway');midway.util.readJsonFile('data.json');Note the Use of midway.util to access the method readJsonFileWrite to file - writeFile()This API allows to write file contents to a filemidway.util.writeFile(filePath, file data, callback);The following attributes are supported: Attribute Description Required file path Absolute or relative location of file Yes file data contents to write Yes callback Callback function after writeFile completes Yes Examplevar midway = require('testarmada-midway');midway.util.writeFile('hello.txt', 'hello world blah blah', function () { console.log('Wrote to file successfully');});Note the Use of midway.util to access the method writeFileDelete file - deleteFile()This API allows to write file contents to a filemidway.util.deleteFile(filePath, callback);The following attributes are supported: Attribute Description Required file location Absolute or relative location of file to delete Yes callback Callback function after deleteFile completes Yes Examplevar midway = require('testarmada-midway');midway.util.deleteFile('filetoDelete.txt', function (err) { if (err) { console.log('Error in deleting file'); }});Note the Use of midway.util to access the method deleteFileCheck if directory exists - checkDirectoryExists()This API allows to check if a directory exists. Returns true if directory exists, false otherwise.midway.util.checkDirectoryExists(directoryPath);The following attributes are supported: Attribute Description Required directory path Location of directory to check Yes Examplevar midway = require('testarmada-midway');midway.util.checkDirectoryExists('/home/data');Note the Use of midway.util to access the method checkDirectoryExistsCheck if file exists - checkFileExists()This API allows to check if a file exists. Returns true if file exists, false otherwise.midway.util.checkFileExists(filePath);The following attributes are supported: Attribute Description Required file path Location of file to check Yes Examplevar midway = require('testarmada-midway');midway.util.checkFileExists('/home/data');Note the Use of midway.util to access the method checkFileExistsSet Log level - setLogLevel()This API allows to set log level on Midwaymidway.log.setLogLevel(logLevel); // when using MidwayorLogger.setLogLevel(logLevel); // when using Midway-LoggerThe following attributes are supported: Attribute Description Required logLevel Log level you want to set .Valid values (warn/info/debug/error) Yes Examplevar midway = require('testarmada-midway');midway.log.setLogLevel('debug');orcurl -X GET http://localhost:8080/midway/api/setloglevel/debugGet Log level - getLogLevel()This API allows to get the current log level on Midwaymidway.log.getLogLevel(); // when using Midwayor Logger.getLogLevel(); // when using Midway-LoggerExamplevar midway = require('testarmada-midway');midway.log.getLogLevel();orvar Logger = require('testarmada-midway'-logger');Logger.getLogLevel();orcurl -X GET http://localhost:8080/midway/api/getloglevelReset Log level - resetLogLevel()This API allows to reset the log level of Midway to info (Default log level)midway.log.resetLogLevel();or Logger.resetLogLevel();Examplevar midway = require('testarmada-midway');midway.log.resetLogLevel();orvar Logger = require('testarmada-midway'-logger');Logger.resetLogLevel();or curl -X GET http://localhost:8080/midway/api/resetloglevel",
"url": "/documentation/Mocking/Native Android/JAVASCRIPT/API Guide"
},
"documentation-functional-testing-rweb-javascript-training-guide": {
"title": "Training Guide",
"content": "30 minSetupCovered topicsPrerequisitesSetupRun demo tests locallyStart50 minrWeb TestingCovered topicsPrerequisitesBuilt-in browser testingRemote browser testingStart50 minMagellanCovered topicsMagellan introductionMagellan usageConfigure test profilesStart50 minTests FrameworkCovered topicsTests framework structurePage Object propertiesStart",
"url": "/documentation/Functional Testing/rWeb/JAVASCRIPT/Training Guide/"
},
"documentation-functional-testing-rweb-javascript-introduction": {
"title": "Introduction",
"content": "SummaryThe functional JS Test Development Kit (TDK) is a set of tools for making cross-browser end-to-end testing fast, user-friendly, and valuable at scale, across large teams, without those annoying false positives.The following tools are part of the functional JS TDK: Magellan - Magellan is a massively parallel test runner. By distributing tests across available CPU cores, Magellan blazes through long test suites in a fraction of the time, aggregating results in one friendly report. Nightwatch-Extra - Nightwatch is a friendly NodeJS-based wrapper for Selenium, allowing developers to author tests in a way that’s easy to learn and quick to iterate on. The Nightwatch-Extra adapter is the first of many adapters to come for bringing other webdriver wrappers into the TestArmada ecosystem. Executor - Executor acts as a middle layer between magellan and test framework to drive test run (via framework) based on a specific need (differentiated by executing environments). Reporter - Magellan can give you various test reports if configured with a proper reporter. There are already several reporters available in Testarmada to grab, however the simple API Testarmada exposes also allows to create a customized reporter in an easy way. Admiral - Like a tree falling in the woods, a test report that nobody reads doesn’t make a sound. Admiral is a beautiful dashboard that makes it easy to check the latest cross-browser test results, and to spot trends and sources of failures. Use CaseBuilt for Walmart ScaleBuilt at WalmartLabs to drive quality for the world’s largest retailer, TestArmada is battle-tested, enterprise-grade, and ready to take on end-to-end testing for your site.Results You Can TrustTestArmada won’t waste your team’s time or erode its trust with annoying false-positives. When failures occur, TestArmada intelligently retries the tests to smooth over common sources of “test flake”.More Signal, Less NoiseThe functional JS TDK tells you everything you need to know, and nothing you don’t. Notifications occur in real-time when tests fail, and a beautiful dashboard always shows the latest status for each suite.ImpactWith the functional JS TDK, WalmartLabs has made end-to-end testing part of the shared culture between dev & QA. Both organizations collaborate to ensure quality at all levels development, staging, and production.Feature ListThe functional JS TDK supports: Frameworks - Nightwatch & Mocha Reporters - xunit, json & mongo db Clouds - Saucelabs & Testobject ",
"url": "/documentation/Functional Testing/rWeb/JAVASCRIPT/Introduction"