How to use cleanseError method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

index.js

Source: index.js Github

copy
1"use strict";
2var typescript_overrides_1 = require("./lib/typescript-overrides");
3var Promise = require("bluebird");
4var _ = require("lodash");
5var webpack = require("webpack");
6var deferred_1 = require("./deferred");
7var path = require('path');
8var debug = require('debug')('cypress:webpack');
9var debugStats = require('debug')('cypress:webpack:stats');
10// bundle promises from input spec filename to output bundled file paths
11var bundles = {};
12// we don't automatically load the rules, so that the babel dependencies are
13// not required if a user passes in their own configuration
14var getDefaultWebpackOptions = function () {
15    debug('load default options');
16    return {
17        mode: 'development',
18        module: {
19            rules: [
20                {
21                    test: /\.jsx?$/,
22                    exclude: [/node_modules/],
23                    use: [
24                        {
25                            loader: 'babel-loader',
26                            options: {
27                                presets: ['@babel/preset-env'],
28                            },
29                        },
30                    ],
31                },
32            ],
33        },
34    };
35};
36var replaceErrMessage = function (err, partToReplace, replaceWith) {
37    if (replaceWith === void 0) { replaceWith = ''; }
38    err.message = _.trim(err.message.replace(partToReplace, replaceWith));
39    if (err.stack) {
40        err.stack = _.trim(err.stack.replace(partToReplace, replaceWith));
41    }
42    return err;
43};
44var cleanModuleNotFoundError = function (err) {
45    var message = err.message;
46    if (!message.includes('Module not found'))
47        return err;
48    // Webpack 5 error messages are much less verbose. No need to clean.
49    if ('NormalModule' in webpack) {
50        return err;
51    }
52    var startIndex = message.lastIndexOf('resolve ');
53    var endIndex = message.lastIndexOf("doesn't exist") + "doesn't exist".length;
54    var partToReplace = message.substring(startIndex, endIndex);
55    var newMessagePart = "Looked for and couldn't find the file at the following paths:";
56    return replaceErrMessage(err, partToReplace, newMessagePart);
57};
58var cleanMultiNonsense = function (err) {
59    var message = err.message;
60    var startIndex = message.indexOf('@ multi');
61    if (startIndex < 0)
62        return err;
63    var partToReplace = message.substring(startIndex);
64    return replaceErrMessage(err, partToReplace);
65};
66var quietErrorMessage = function (err) {
67    if (!err || !err.message)
68        return err;
69    err = cleanModuleNotFoundError(err);
70    err = cleanMultiNonsense(err);
71    return err;
72};
73/**
74 * Webpack preprocessor configuration function. Takes configuration object
75 * and returns file preprocessor.
76 * @example
77  ```
78  on('file:preprocessor', webpackPreprocessor(options))
79  ```
80 */
81// @ts-ignore
82var preprocessor = function (options) {
83    if (options === void 0) { options = {}; }
84    debug('user options: %o', options);
85    // we return function that accepts the arguments provided by
86    // the event 'file:preprocessor'
87    //
88    // this function will get called for the support file when a project is loaded
89    // (if the support file is not disabled)
90    // it will also get called for a spec file when that spec is requested by
91    // the Cypress runner
92    //
93    // when running in the GUI, it will likely get called multiple times
94    // with the same filePath, as the user could re-run the tests, causing
95    // the supported file and spec file to be requested again
96    return function (file) {
97        var filePath = file.filePath;
98        debug('get', filePath);
99        // since this function can get called multiple times with the same
100        // filePath, we return the cached bundle promise if we already have one
101        // since we don't want or need to re-initiate webpack for it
102        if (bundles[filePath]) {
103            debug("already have bundle for " + filePath);
104            return bundles[filePath].promise;
105        }
106        var defaultWebpackOptions = getDefaultWebpackOptions();
107        // we're provided a default output path that lives alongside Cypress's
108        // app data files so we don't have to worry about where to put the bundled
109        // file on disk
110        var outputPath = path.extname(file.outputPath) === '.js'
111            ? file.outputPath
112            : file.outputPath + ".js";
113        var entry = [filePath].concat(options.additionalEntries || []);
114        var watchOptions = options.watchOptions || {};
115        // user can override the default options
116        var webpackOptions = _
117            .chain(options.webpackOptions)
118            .defaultTo(defaultWebpackOptions)
119            .defaults({
120            mode: defaultWebpackOptions.mode,
121        })
122            .assign({
123            // we need to set entry and output
124            entry: entry,
125            output: {
126                path: path.dirname(outputPath),
127                filename: path.basename(outputPath),
128            },
129        })
130            .tap(function (opts) {
131            if (opts.devtool === false) {
132                // disable any overrides if we've explictly turned off sourcemaps
133                (0, typescript_overrides_1.overrideSourceMaps)(false, options.typescript);
134                return;
135            }
136            debug('setting devtool to inline-source-map');
137            opts.devtool = 'inline-source-map';
138            // override typescript to always generate proper source maps
139            (0, typescript_overrides_1.overrideSourceMaps)(true, options.typescript);
140        })
141            .value();
142        debug('webpackOptions: %o', webpackOptions);
143        debug('watchOptions: %o', watchOptions);
144        if (options.typescript)
145            debug('typescript: %s', options.typescript);
146        debug("input: " + filePath);
147        debug("output: " + outputPath);
148        var compiler = webpack(webpackOptions);
149        var firstBundle = (0, deferred_1.createDeferred)();
150        // cache the bundle promise, so it can be returned if this function
151        // is invoked again with the same filePath
152        bundles[filePath] = {
153            promise: firstBundle.promise,
154            // we will resolve all reject everything in this array when a compile completes in the `handle` function
155            deferreds: [firstBundle],
156            initial: true,
157        };
158        var rejectWithErr = function (err) {
159            err = quietErrorMessage(err);
160            // @ts-ignore
161            err.filePath = filePath;
162            debug("errored bundling " + outputPath, err.message);
163            var lastBundle = bundles[filePath].deferreds[bundles[filePath].deferreds.length - 1];
164            lastBundle.reject(err);
165            bundles[filePath].deferreds.length = 0;
166        };
167        // this function is called when bundling is finished, once at the start
168        // and, if watching, each time watching triggers a re-bundle
169        var handle = function (err, stats) {
170            if (err) {
171                debug('handle - had error', err.message);
172                return rejectWithErr(err);
173            }
174            var jsonStats = stats.toJson();
175            // these stats are really only useful for debugging
176            if (jsonStats.warnings.length > 0) {
177                debug("warnings for " + outputPath + " %o", jsonStats.warnings);
178            }
179            if (stats.hasErrors()) {
180                err = new Error('Webpack Compilation Error');
181                var errorsToAppend = jsonStats.errors
182                    // remove stack trace lines since they're useless for debugging
183                    .map(cleanseError)
184                    // multiple errors separated by newline
185                    .join('\n\n');
186                err.message += "\n" + errorsToAppend;
187                debug('stats had error(s) %o', jsonStats.errors);
188                return rejectWithErr(err);
189            }
190            debug('finished bundling', outputPath);
191            if (debugStats.enabled) {
192                /* eslint-disable-next-line no-console */
193                console.error(stats.toString({ colors: true }));
194            }
195            // resolve with the outputPath so Cypress knows where to serve
196            // the file from
197            // Seems to be a race condition where changing file before next tick
198            // does not cause build to rerun
199            Promise.delay(0).then(function () {
200                if (!bundles[filePath]) {
201                    return;
202                }
203                bundles[filePath].deferreds.forEach(function (deferred) {
204                    deferred.resolve(outputPath);
205                });
206                bundles[filePath].deferreds.length = 0;
207            });
208        };
209        // this event is triggered when watching and a file is saved
210        var plugin = { name: 'CypressWebpackPreprocessor' };
211        var onCompile = function () {
212            debug('compile', filePath);
213            var nextBundle = (0, deferred_1.createDeferred)();
214            bundles[filePath].promise = nextBundle.promise;
215            bundles[filePath].deferreds.push(nextBundle);
216            bundles[filePath].promise.finally(function () {
217                debug('- compile finished for %s, initial? %s', filePath, bundles[filePath].initial);
218                // when the bundling is finished, emit 'rerun' to let Cypress
219                // know to rerun the spec, but NOT when it is the initial
220                // bundling of the file
221                if (!bundles[filePath].initial) {
222                    file.emit('rerun');
223                }
224                bundles[filePath].initial = false;
225            })
226                // we suppress unhandled rejections so they don't bubble up to the
227                // unhandledRejection handler and crash the process. Cypress will
228                // eventually take care of the rejection when the file is requested.
229                // note that this does not work if attached to latestBundle.promise
230                // for some reason. it only works when attached after .finally  ¯\_(ツ)_/¯
231                .suppressUnhandledRejections();
232        };
233        // when we should watch, we hook into the 'compile' hook so we know when
234        // to rerun the tests
235        if (file.shouldWatch) {
236            if (compiler.hooks) {
237                // TODO compile.tap takes "string | Tap"
238                // so seems we just need to pass plugin.name
239                // @ts-ignore
240                compiler.hooks.compile.tap(plugin, onCompile);
241            }
242            else if ('plugin' in compiler) {
243                // @ts-ignore
244                compiler.plugin('compile', onCompile);
245            }
246        }
247        var bundler = file.shouldWatch ? compiler.watch(watchOptions, handle) : compiler.run(handle);
248        // when the spec or project is closed, we need to clean up the cached
249        // bundle promise and stop the watcher via `bundler.close()`
250        file.on('close', function (cb) {
251            if (cb === void 0) { cb = function () { }; }
252            debug('close', filePath);
253            delete bundles[filePath];
254            if (file.shouldWatch) {
255                // in this case the bundler is webpack.Compiler.Watching
256                if (bundler && 'close' in bundler) {
257                    bundler.close(cb);
258                }
259            }
260        });
261        // return the promise, which will resolve with the outputPath or reject
262        // with any error encountered
263        return bundles[filePath].promise;
264    };
265};
266// provide a clone of the default options
267Object.defineProperty(preprocessor, 'defaultOptions', {
268    get: function () {
269        debug('get default options');
270        return {
271            webpackOptions: getDefaultWebpackOptions(),
272            watchOptions: {},
273        };
274    },
275});
276// for testing purposes, but do not add this to the typescript interface
277// @ts-ignore
278preprocessor.__reset = function () {
279    bundles = {};
280};
281// for testing purposes, but do not add this to the typescript interface
282// @ts-ignore
283preprocessor.__bundles = function () {
284    return bundles;
285};
286// @ts-ignore - webpack.StatsError is unique to webpack 5
287// TODO: Remove this when we update to webpack 5.
288function cleanseError(err) {
289    var msg = typeof err === 'string' ? err : err.message;
290    return msg.replace(/\n\s*at.*/g, '').replace(/From previous event:\n?/g, '');
291}
292module.exports = preprocessor;
293
Full Screen

ns.addresses.js

Source: ns.addresses.js Github

copy
1// Dependencies:  JQuery, JQuery Unobtrusive Validation, & KnockoutJS
2// The following lines enable VS Intellisense for jquery & knockout
3// and the triple slash IS required.
4/// <reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2-vsdoc.js" />
5/// <reference path="http://dev.iceburg.net/jquery/jqModal/jqModal.js" />
6/// <reference path="~/Scripts/jquery.validate.unobtrusive.js" />
7/// <reference path="~/Scripts/knockout-2.1.0.debug.js" />
8/// <reference path="~/Scripts/knockout.mapping-latest.debug.js" />
9
10// NOTES: You will see the use of prototype all over the place.  Which is why
11// you will see .call & .apply all over the place.  This is a best practice for performance
12// purposes.  
13
14// Prototype functions are static functions.  However you will see the use of
15// .call or .apply to those calls.  .call & .apply set the object to reference
16// within those functions for the 'this' keyword.
17
18// You will also see creating 'refThis' variable and assigning the this keyword
19// value to it.  The refThis will be included in a function which may not be called
20// until a later time.  When that function is call the this keyword will not reflect
21// the object at the time the function creating function was called
22
23
24(function (rootObj) {
25	var isUndefined = function (evalObj) { return typeof (evalObj) === 'undefined'; };
26
27	if (isUndefined(rootObj.ns)) rootObj.ns = {};
28	if (isUndefined(rootObj.ns.addressEditor)) {
29
30		var addressEditor = function (settings) {
31			try {
32				var refThis = this;
33
34				// init stack
35				_.initSettings.call(refThis, settings);
36				_.initCleanseWindow.call(refThis);
37				_.registerWithEditors.call(refThis, settings.editorID);
38
39				_.initViewModel.call(refThis);
40				_.initEvents.call(refThis);
41				_.initFuncs.call(refThis);
42
43				// Apply binding and then register this editor with global list of editors
44				_.initTemplate.call(refThis);
45
46			} catch (ex) {
47				alert(this.settings.termTranslations.initError + '\r\n' + ex);
48			}
49		};
50
51		addressEditor.prototype.consts = {
52			boolOverride:
53            {
54            	inherit: 0,
55            	yes: 1,
56            	no: 2
57            },
58			cleansingMode:
59            {
60            	inherit: 0,
61            	none: 1,
62            	propose: 2,
63            	required: 3
64            },
65			cleanseResult:
66            {
67            	Unknown: 0,
68            	Error: 1,
69            	Success: 2
70            }
71		};
72
73		var consts = addressEditor.prototype.consts;
74
75		addressEditor.prototype._ = {
76
77			initSettings: function (settings) {
78				// create a new object {}, deep copy/merge static settings and editor settings into it
79				this.settings = $.extend(true, {}, _.defaults.settings, settings);
80				this.settings.templateDivIndex = '';
81				this.settings.countryTemplateAjaxLink = $('#' + this.settings.templateDivID + 'CountryTemplateLink').attr('href');
82				this.settings.scrubAddressAjaxLink = $('#' + this.settings.templateDivID + 'ScrubAddressLink').attr('href');
83				this.settings.postalCodeLookupAjaxLink = $('#' + this.settings.templateDivID + 'PostalCodeLookupLink').attr('href');
84
85			},
86
87			initCleanseWindow: function () {
88				this.cleanseWindow = $('#' + this.settings.templateDivID + this.settings.templateDivIndex + 'CleanseWindow')
89				//  ;  // If this line is commented out then I forgot to comment the one below out before checking in
90                    .attr('style', 'display: none; position: fixed; top: 17%;left: 50%;margin-left: -300px; width: 600px;');
91
92
93
94				this.cleanseWindow.jqm({
95
96					modal: true
97                    , trigger: false
98                    , onShow: function (h) {
99                    	h.w.fadeIn();
100                    }
101				});
102
103			},
104
105
106			defaults:
107            {
108            	settings:
109                {
110                	address: {},
111                	editorID: 'globalAddressEditor',
112                	templateDivID: 'globalAddressEditor',
113                	termTranslations:
114                    {
115                    	initError: 'An error has occurred while attempting to '
116                        + 'initialize an address entry section of this page.\r\n',
117                    	commError: 'An error occurred while connecting to the server '
118                        + 'to attempt to verify your address'
119                    },
120                	countries: [],
121                	countryStateProvinces: [],
122                	//stateProvinceCities: [],
123                	phoneTypes: [],
124                	countryOverrideSettings: {},
125                	/// <summary>
126                	/// Enables address scrubbing, this property changes per country.
127                	/// Upon country changing the template call shall provide 
128                	/// the globaAddressEditor ID as a a parameter to specify 
129                	/// this instance of the address editor so that it may 
130                	/// update this setting, the model, and the postalCodeLookup setting
131                	/// </summary>
132                	cleansingMode: consts.cleansingMode.none, // 'required', 'propose'
133                	/// <summary>
134                	/// Enables postal code lookup upon entering a postal code.
135                	/// this property changes per market.  Upon triggering the 
136                	/// application shall call an AJAX service to obtain updated 
137                	/// model information providing the existing model and 
138                	/// rebind the UI.  Because country codes will not change 
139                	/// there is no need to refresh the template.
140                	///</summary>
141                	allowPostalCodeLookup: consts.boolOverride.no
142                },
143
144            	country:
145                {
146                	countryCode: '',
147                	countryID: '',
148                	countryName: ''
149                },
150
151            	// countryCode='' is the common overrides
152            	// countryCode='...' is a country specific override
153            	countryOverrideSetting:
154                {
155                	countryCode: '',
156                	allowPostalCodeLookup: consts.boolOverride.inherit,
157                	cleansingMode: consts.cleansingMode.inherit,
158                	fieldOverrides: {}
159                },
160
161            	countryFieldOverrideSetting:
162                {
163                	fieldEnabled: 0,
164                	fieldIncluded: 0,
165                	fieldName: '',
166                	label: ''
167                },
168
169            	viewModel: {
170            		showField: function (fieldName, showByDefault) {
171
172            			var editor = ns.addressEditors[this.editorName()];
173            			var address = editor.viewModel.address;
174            			var countryCode = address.CountryCode();
175
176            			var commonSettings = editor.settings.countryOverrideSettings[''];
177            			var commonFieldSetting = commonSettings && commonSettings.fieldOverrides[fieldName] !== undefined ? commonSettings.fieldOverrides[fieldName] : null;
178
179            			var countrySpecificSettings = editor.settings.countryOverrideSettings[countryCode];
180            			var countrySpecificFieldSetting = countrySpecificSettings && countrySpecificSettings.fieldOverrides[fieldName] !== undefined ? countrySpecificSettings.fieldOverrides[fieldName] : null;
181
182            			return countrySpecificFieldSetting && countrySpecificFieldSetting.fieldIncluded == consts.boolOverride.yes
183                            ? true
184                            : countrySpecificFieldSetting && countrySpecificFieldSetting.fieldIncluded == consts.boolOverride.no
185                            ? false
186                            : commonFieldSetting && commonFieldSetting.fieldIncluded == consts.boolOverride.yes
187                            ? true
188                            : commonFieldSetting && commonFieldSetting.fieldIncluded == consts.boolOverride.no
189                            ? false
190                            : showByDefault;
191
192            		},
193
194            		enableField: function (fieldName, enableByDefault) {
195            			var editor = ns.addressEditors[this.editorName()];
196            			var address = editor.viewModel.address;
197            			if (editor.viewModel.cleanseInProgress()) return false;
198
199            			switch (fieldName) {
200            				case 'CountryCode':
201            					if (
202                                    editor.viewModel.postalCodeLookupInProgress()
203                                    || editor.viewModel.showingCleanseWindow()
204                                )
205            						return false;
206            				case 'City':
207            				case 'County':
208            				case 'State':
209            				case 'StateID':
210            				case 'StateCode':
211            				case 'StateProvince':
212            				case 'StateProvinceID':
213            				case 'StateProvinceCode':
214            					if (editor.viewModel.postalCodeLookupInProgress()) return false;
215            					break;
216            				default:
217            					break;
218            			}
219
220            			var countryCode = address.CountryCode();
221
222            			var commonSettings = editor.settings.countryOverrideSettings[''];
223            			var commonFieldSetting = commonSettings && commonSettings.fieldOverrides[fieldName] !== undefined ? commonSettings.fieldOverrides[fieldName] : null;
224
225            			var countrySpecificSettings = editor.settings.countryOverrideSettings[countryCode];
226            			var countrySpecificFieldSetting = countrySpecificSettings && countrySpecificSettings.fieldOverrides[fieldName] !== undefined ? countrySpecificSettings.fieldOverrides[fieldName] : null;
227
228            			return countrySpecificFieldSetting && countrySpecificFieldSetting.fieldEnabled == consts.boolOverride.yes
229                            ? true
230                            : countrySpecificFieldSetting && countrySpecificFieldSetting.fieldEnabled == consts.boolOverride.no
231                            ? false
232                            : commonFieldSetting && commonFieldSetting.fieldEnabled == consts.boolOverride.yes
233                            ? true
234                            : commonFieldSetting && commonFieldSetting.fieldEnabled == consts.boolOverride.no
235                            ? false
236                            : enableByDefault;
237
238            		},
239
240            		postalCodeLookupSupported: function () {
241            			var editor = ns.addressEditors[this.editorName()];
242            			return editor.settings.allowPostalCodeLookup == consts.boolOverride.yes;
243            		},
244
245            		postalCodeLookupInProgress: false,
246
247            		postalCodeLookupErrorOccurred: false,
248
249            		postalCodeLookupError: '',
250
251            		postalCodeLookupEmpty: false,
252
253            		cleanseInProgress: false,
254
255            		showingCleanseWindow: false,
256
257            		selectSuggestion: function (data, root) {
258            			return function () {
259            				var editor = ns.addressEditors[root.editorName()];
260            				var vm = editor.viewModel;
261            				vm.selectedSuggestion(data);
262            			};
263            		},
264
265            		selectedSuggestion: null,
266
267            		cancelCleansePrompt: function () {
268            			this.cancelCleansePromptTriggered(true);
269            		},
270
271            		cancelCleansePromptTriggered: false,
272
273            		confirmCleansePromptTriggered: false,
274
275            		retryCleanseTriggered: false,
276
277            		cleanseErrorOccurred: false,
278
279            		cleanseError: '',
280
281            		canRetryCleanse: true,
282
283            		canContinueWithProvidedAddress: function () {
284            			var editor = ns.addressEditors[this.editorName()];
285            			return _.getCleansingMode.call(editor) != consts.cleansingMode.required;
286            		},
287
288            		retryCleanse: function () {
289            			this.retryCleanseTriggered(true);
290            		},
291
292            		continueWithProvidedAddress: function () {
293            			var editor = ns.addressEditors[this.editorName()];
294            			if ($(editor.cleanseWindow).find('form').valid()) {
295            				this.confirmCleansePromptTriggered(true);
296            			}
297            		},
298
299            		lists: {
300            			suggestions: [
301
302                        ],
303            			countries: [],
304            			phoneTypes: [],
305            			countryStateProvinces: [],
306            			//stateProvinceCities: [],
307            			postalCodeCities: [],
308            			postalCodeCounties: [],
309            			postalCodeStateProvinces: []
310            		},
311
312            		address: {
313            			AddressID: null,
314            			Attention: '',
315            			FirstName: '',
316            			LastName: '',
317            			Address1: '',
318            			Address2: '',
319            			Address3: '',
320            			PostalCode: '',
321            			City: '',
322            			County: '',
323            			StateProvince: '',
324            			StateProvinceID: '',
325            			Country: '',
326            			CountryCode: '',
327            			CountryID: 0,
328            			ScrubbedGuid: ''
329            		}
330            	}
331            },
332
333			initViewModel: function () {
334				var viewModel = $.extend(true, { editorName: this.settings.editorID }, _.defaults.viewModel);
335				$.extend(true, viewModel.address, this.settings.address);
336				$.extend(true, viewModel.lists.countries, this.settings.countries);
337				$.extend(true, viewModel.lists.countryStateProvinces, this.settings.countryStateProvinces);
338				//$.extend(true, viewModel.lists.stateProvinceCities, this.settings.stateProvinceCities);
339				$.extend(true, viewModel.lists.phoneTypes, this.settings.phoneTypes);
340				this.viewModel = ko.mapping.fromJS(viewModel);
341			},
342
343			initTemplate: function () {
344				this.settings.templateDiv = $('#' + this.settings.templateDivID + this.settings.templateDivIndex);
345				_.hookupTemplate.apply(this);
346			},
347
348			hookupTemplate: function () {
349				var refThis = this;
350				window.setTimeout(function () {
351					var forms = $(refThis.settings.templateDiv).find('form');
352					forms.validate({
353						errorPlacement: function (error, element) {
354							$(error).fadeIn('slow');
355						}
356					});
357					forms.removeData('validator');
358					forms.removeData('unobtrusiveValidation');
359					$.validator.unobtrusive.parse(forms);
360					ko.applyBindings(refThis.viewModel, $(refThis.settings.templateDiv)[0]);
361					//}, 1000 * 30); // pause to allow dev to modify bindings during debugging
362				}, 0);
363			},
364
365			unhookTemplate: function () {
366				ko.cleanNode($(this.settings.templateDiv)[0]);
367			},
368
369			shouldExecutePostalCodeLookup: function () {
370				var editor = this;
371				var address = editor.viewModel.address;
372				var countryCode = address.CountryCode();
373
374				var commonSettings = editor.settings.countryOverrideSettings[''];
375				var countrySpecificSettings = editor.settings.countryOverrideSettings[countryCode];
376
377
378				return countrySpecificSettings && countrySpecificSettings.allowPostalCodeLookup == consts.boolOverride.yes
379                            ? true
380                            : countrySpecificSettings && countrySpecificSettings.allowPostalCodeLookup == consts.boolOverride.no
381                            ? false
382                            : commonSettings && commonSettings.allowPostalCodeLookup == consts.boolOverride.yes
383                            ? true
384                            : commonSettings && commonSettings.allowPostalCodeLookup == consts.boolOverride.no
385                            ? false
386                            : this.settings.allowPostalCodeLookup == consts.boolOverride.yes
387                            ? true
388                            : false;
389			},
390
391			shouldPromptAddressCleansing: function () {
392
393				var editor = this;
394				var address = editor.viewModel.address;
395				var countryCode = address.CountryCode();
396
397				var commonSettings = editor.settings.countryOverrideSettings[''];
398				var countrySpecificSettings = editor.settings.countryOverrideSettings[countryCode];
399
400				return countrySpecificSettings && countrySpecificSettings.cleansingMode != consts.cleansingMode.none
401                            ? true
402                            : commonSettings && commonSettings.cleansingMode != consts.cleansingMode.none
403                            ? true
404                            : this.settings.cleansingMode == consts.cleansingMode.none
405                            ? true
406                            : false;
407			},
408
409			getCleansingMode: function () {
410
411				var editor = this;
412				var address = editor.viewModel.address;
413				var countryCode = address.CountryCode();
414
415				var commonSettings = editor.settings.countryOverrideSettings[''];
416				var countrySpecificSettings = editor.settings.countryOverrideSettings[countryCode];
417
418
419				return countrySpecificSettings && countrySpecificSettings.cleansingMode != consts.cleansingMode.inherit
420                    ? countrySpecificSettings.cleansingMode
421                    : commonSettings && commonSettings.cleansingMode != consts.cleansingMode.inherit
422                    ? commonSettings.cleansingMode
423                    : consts.cleansingMode.none;
424			},
425
426			initEvents: function () {
427				var refThis = this;
428
429				// create a flag to allow changes made during the event handling
430				// of country code changes without re-triggering the event
431				var alreadyHandlingCountryChanges = false;
432
433				var postalCodeChange = function (newValue) {
434					if (_.shouldExecutePostalCodeLookup.call(refThis)) {
435						_.funcs.executePostalCodeLookup.call(refThis, arguments);
436					}
437				};
438
439				var asyncPostalCodeChange = function () {
440					if (refThis.viewModel.postalCodeLookupInProgress()) return;
441					// var args = $.merge(arguments, [(event != null && event.srcElement != null) ? event.srcElement : null]);
442					var args = arguments;
443					_.funcs.asyncFire.call(refThis, postalCodeChange, args);
444				};
445
446				this.viewModel.address.PostalCode.subscribe(asyncPostalCodeChange);
447
448				var countryCodeChange = function (whichField) {
449
450					// TODO : Determine which value was changes and then 
451					// cross reference update the other country related properties.
452					// ex update name and ID if code was changed
453					// or update code and ID if name was changed
454					// or update name and code if ID was changed
455
456					try {
457						// var triggeringElement = arguments[arguments.length - 1];
458						// if (!$(triggeringElement).valid()) return;
459						// var id = $(triggeringElement)[0].id;
460
461						var refThis = this;
462
463						if (refThis.settings.templateDivIndex == '') refThis.settings.templateDivIndex = 0;
464						refThis.settings.templateDivIndex = refThis.settings.templateDivIndex + 1;
465						var oldDiv = refThis.settings.templateDiv;
466						$('<div style="display:none;" id="' + this.settings.templateDivID + this.settings.templateDivIndex + '"></div>').insertAfter(refThis.settings.templateDiv);
467
468						$.post(this.settings.countryTemplateAjaxLink, { uiModel: _.getAddressModel.apply(refThis), clientSideAddressObjID: refThis.settings.editorID, clientSideAddressHtmlID: refThis.settings.templateDivID + refThis.settings.templateDivIndex }, function (results) {
469
470							_.unhookTemplate.apply(refThis);
471							$('#' + refThis.settings.templateDivID + refThis.settings.templateDivIndex).html(results);
472							_.initTemplate.apply(refThis);
473							_.initCleanseWindow.apply(refThis);
474							// _.hookupTemplate.apply(refThis);
475							// $('#' + id).focus();
476							oldDiv.remove();
477							$(refThis.settings.templateDiv).show();
478						});
479
480					} finally {
481						alreadyHandlingCountryChanges = false;
482					}
483				};
484				var asyncCountryCodeChange = function () {
485					if (alreadyHandlingCountryChanges) return;
486					alreadyHandlingCountryChanges = true;
487					// var args = $.merge(arguments, [(event != null && event.srcElement != null) ? event.srcElement : null]);
488					var args = arguments;
489					_.funcs.asyncFire.call(refThis, countryCodeChange, args);
490				};
491				var asynxCountryCodeChange_Code = function () { asyncCountryCodeChange.apply(refThis, ['code']); }
492				var asynxCountryCodeChange_ID = function () { asyncCountryCodeChange.apply(refThis, ['id']); }
493				var asynxCountryCodeChange_Name = function () { asyncCountryCodeChange.apply(refThis, ['name']); }
494
495				this.viewModel.address.CountryCode.subscribe(asynxCountryCodeChange_Code);
496				this.viewModel.address.CountryID.subscribe(asynxCountryCodeChange_ID);
497				this.viewModel.address.Country.subscribe(asynxCountryCodeChange_Name);
498			},
499
500			registerWithEditors: function (editorID) {
501				rootObj.ns.addressEditors[editorID] = this;
502			},
503
504			isFunction: function (value) {
505				return !isUndefined(value)
506                && value !== null
507                && typeof (value) === 'function';
508			},
509
510			isPrimitive: function (value) {
511				return !isUndefined(value)
512                && value !== null
513                && typeof (value) !== 'object'
514                && typeof (value) !== 'function';
515			},
516
517			gettext: function (sourceObj, prop, optionalDefaultValue) {
518				var result = !isUndefined(sourceObj) && !_.isPrimitive(sourceObj) && _.isPrimitive(sourceObj[prop])
519                ? sourceObj[prop]
520                : !isUndefined(optionalDefaultValue) ? optionalDefaultValue : '';
521				return result;
522			},
523
524			getAddressModel: function () {
525				var model = ko.mapping.toJS(this.viewModel);
526				return model.address;
527			},
528
529			initFuncs: function () {
530				var refThis = this;
531				this.promptAddressCleansing = function () { _.funcs.asyncFire.call(refThis, _.funcs.promptAddressCleansing, arguments); };
532				this.getAddress = function () { _.funcs.asyncFire.call(refThis, _.funcs.getAddress, arguments); };
533				this.valid = function () {
534					return $(this.settings.templateDiv).find('form').valid();
535				};
536			},
537
538			funcs:
539            {
540            	asyncFire: function (func, args) {
541            		var refThis = this;
542            		var refArgs = args;
543            		window.setTimeout(function () { func.apply(refThis, refArgs); }, 0);
544            	},
545            	promptAddressCleansing: function (successCallback, failCallback) {
546            		var refThis = this;
547            		var confirm, cancel, select, retryCleanse;
548
549            		refThis.viewModel.cleanseInProgress(true);
550
551            		this.viewModel.showingCleanseWindow(true);
552
553            		var clearSubscribers = function () {
554            			if (confirm != null) confirm.dispose();
555            			if (cancel != null) cancel.dispose();
556            			if (select != null) select.dispose();
557
558            			refThis.viewModel.confirmCleansePromptTriggered(false);
559            			refThis.viewModel.cancelCleansePromptTriggered(false);
560            		};
561
562            		select = refThis.viewModel.selectedSuggestion.subscribe(function () {
563            			var newVal = refThis.viewModel.selectedSuggestion();
564            			if (newVal == null) return;
565            			try {
566            				var model = ko.mapping.toJS(newVal.address);
567
568            				clearSubscribers();
569            				refThis.cleanseWindow.jqmHide();
570            				refThis.viewModel.showingCleanseWindow(false);
571            				if (_.isFunction(successCallback))
572            					successCallback(model);
573
574
575            			} finally {
576            				refThis.selectedSuggestion(null);
577            			}
578            		});
579
580            		confirm = refThis.viewModel.confirmCleansePromptTriggered.subscribe(function () {
581            			clearSubscribers();
582            			refThis.cleanseWindow.jqmHide();
583            			refThis.viewModel.showingCleanseWindow(false);
584            			if (_.isFunction(successCallback))
585            				successCallback(_.getAddressModel.apply(refThis));
586            		});
587
588            		cancel = refThis.viewModel.cancelCleansePromptTriggered.subscribe(function () {
589            			clearSubscribers();
590            			refThis.cleanseWindow.jqmHide();
591            			refThis.viewModel.showingCleanseWindow(false);
592            			if (_.isFunction(failCallback))
593            				failCallback();
594            		});
595
596            		retryCleanse = refThis.viewModel.retryCleanseTriggered.subscribe(function (newValue) {
597            			if (newValue == false) return;
598
599            			refThis.viewModel.cleanseInProgress(true);
600            			refThis.viewModel.retryCleanseTriggered(false);
601            			refThis.viewModel.lists.suggestions.removeAll();
602            			refThis.viewModel.cleanseErrorOccurred(false);
603            			refThis.viewModel.cleanseError('');
604
605            			$.ajax({
606            				url: refThis.settings.scrubAddressAjaxLink,
607            				data: { fromAddress: _.getAddressModel.apply(refThis) },
608            				success: function (results) {
609            					try {
610            						if (results.Status == consts.cleanseResult.Success) {
611            							refThis.viewModel.lists.suggestions.removeAll();
612
613            							for (var i = 0; i < results.ValidAddresses.length; i++) {
614            								var item = ko.mapping.fromJS({
615            									address: $.extend(true, {},
616            										{
617            											AddressID: null,
618            											Attention: '',
619            											FirstName: '',
620            											LastName: '',
621            											Address1: '',
622            											Address2: '',
623            											Address3: '',
624            											PostalCode: '',
625            											City: '',
626            											County: '',
627            											StateProvince: '',
628            											StateProvinceID: '',
629            											Country: '',
630            											CountryCode: '',
631            											CountryID: 0,
632            											ScrubbedGuid: ''
633            										}, refThis.settings.address, results.ValidAddresses[i])
634            								});
635
636            								if (results.ValidAddresses.length == 1) {
637            									var model = ko.mapping.toJS(item.address);
638
639            									clearSubscribers();
640            									refThis.cleanseWindow.jqmHide();
641            									refThis.viewModel.showingCleanseWindow(false);
642            									if (_.isFunction(successCallback))
643            										successCallback(model);
644            								}
645            								else {
646            									refThis.viewModel.lists.suggestions.push(item);
647            								}
648            							}
649            						} else {
650            							refThis.viewModel.cleanseErrorOccurred(true);
651            							refThis.viewModel.cleanseError(results.Message);
652            						}
653            					} catch (ex) { }
654            				},
655            				error: function (detail, status, ex) {
656            					try {
657            						refThis.viewModel.cleanseErrorOccurred(true);
658            						refThis.viewModel.cleanseError(refThis.settings.termTranslations.commError);
659            					} catch (ex) { }
660            				},
661            				complete: function () {
662            					refThis.viewModel.cleanseInProgress(false);
663            				}
664            			});
665            		});
666
667            		this.viewModel.retryCleanse.apply(refThis.viewModel);
668            		this.cleanseWindow.jqmShow();
669            	},
670            	getAddress: function (successCallback, failCallback) {
671            		if (!$(this.settings.templateDiv).find('form').valid()) {
672            			failCallback();
673            			return;
674            		}
675
676            		if (_.shouldPromptAddressCleansing.call(this))
677            			this.promptAddressCleansing(successCallback, failCallback);
678            		else
679            			successCallback(_.getAddressModel.apply(this));
680            	},
681
682            	executePostalCodeLookup: function () {
683
684            		//            		var srcElement = arguments[arguments.length - 1];
685            		//            		if (!$(srcElement[1]).valid()) return;
686            		var refThis = this;
687            		var countryCode = this.viewModel.address.CountryCode();
688            		var postalCode = this.viewModel.address.PostalCode();
689
690            		// Clear fields
691            		refThis.viewModel.postalCodeLookupEmpty(false);
692            		refThis.viewModel.postalCodeLookupErrorOccurred(false);
693            		refThis.viewModel.postalCodeLookupError('');
694
695            		$.ajax({
696            			url: refThis.settings.postalCodeLookupAjaxLink,
697            			data: { countryCode: countryCode, postalCode: postalCode },
698            			success: function (results) {
699            				try {
700            					refThis.viewModel.lists.postalCodeCities.removeAll();
701            					refThis.viewModel.lists.postalCodeCounties.removeAll();
702            					refThis.viewModel.lists.postalCodeStateProvinces.removeAll();
703
704            					if (results.length > 0) {
705            						for (var i = 0; i < results.length; i++) {
706            							var foundCity = false;
707            							var foundCounty = false;
708            							var foundStateProvince = false;
709
710            							var existingCities = refThis.viewModel.lists.postalCodeCities();
711            							var existingCounties = refThis.viewModel.lists.postalCodeCounties();
712            							var existingStateProvinces = refThis.viewModel.lists.postalCodeStateProvinces();
713
714            							for (var ci = 0; ci < existingCities.length && !foundCity; ci++)
715            								foundCity = existingCities[ci].City == results[i].city ? true : foundCity;
716            							if (!foundCity) refThis.viewModel.lists.postalCodeCities.push({ City: results[i].city });
717
718            							for (var ci = 0; ci < existingCounties.length && !foundCounty; ci++)
719            								foundCounty = existingCounties[ci].County == results[i].county ? true : foundCounty;
720            							if (!foundCounty) refThis.viewModel.lists.postalCodeCounties.push({ County: results[i].county });
721
722            							for (var si = 0; si < existingStateProvinces.length && !foundStateProvince; si++)
723            								foundStateProvince = existingStateProvinces[si].StateProvince == results[i].state && existingStateProvinces[si].StateProvinceID == results[i].stateId ? true : foundStateProvince;
724            							if (!foundStateProvince) refThis.viewModel.lists.postalCodeStateProvinces.push({ StateProvince: results[i].state, StateAbbreviation: results[i].state, StateProvinceID: results[i].stateId });
725            						}
726
727            						refThis.viewModel.postalCodeLookupEmpty(false);
728            						refThis.viewModel.address.City(results[0].city);
729            						refThis.viewModel.address.County(results[0].county);
730            						refThis.viewModel.address.StateProvince(results[0].state);
731            						refThis.viewModel.address.StateProvinceID(results[0].stateId);
732            					} else {
733            						refThis.viewModel.postalCodeLookupEmpty(true);
734            						refThis.viewModel.address.City('');
735            						refThis.viewModel.address.County('');
736            						refThis.viewModel.address.StateProvince('');
737            						refThis.viewModel.address.StateProvinceID('');
738            					}
739
740
741            				} catch (ex) { }
742            			},
743            			error: function (detail, status, ex) {
744            				try {
745            					refThis.viewModel.postalCodeLookupEmpty(true);
746            					refThis.viewModel.postalCodeLookupErrorOccurred(false);
747            					refThis.viewModel.postalCodeLookupError(refThis.settings.termTranslations.commError);
748            				} catch (ex) { }
749            			},
750            			complete: function () {
751            				refThis.viewModel.postalCodeLookupInProgress(false);
752            			}
753            		});
754
755
756
757            	}
758            }
759		};
760
761		// create easy accessor to static prototype functions
762		_ = addressEditor.prototype._;
763		rootObj.ns.addressEditor = addressEditor;
764		rootObj.ns.addressEditors = {};
765	};
766
767
768})(window);
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)