Best JavaScript code snippet using cypress
ExtraInfo.test.js
Source:ExtraInfo.test.js
1/*2 * Copyright (c) 2021 Huawei Device Co., Ltd.3 * Licensed under the Apache License, Version 2.0 (the "License");4 * you may not use this file except in compliance with the License.5 * You may obtain a copy of the License at6 *7 * http://www.apache.org/licenses/LICENSE-2.08 *9 * Unless required by applicable law or agreed to in writing, software10 * distributed under the License is distributed on an "AS IS" BASIS,11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12 * See the License for the specific language governing permissions and13 * limitations under the License.14 */15import account from '@ohos.account.appAccount'16import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index'17const TIMEOUT = 1000;18describe('ActsAccountSetGetExtraInfo', function () {19 function sleep(delay) {20 var start = (new Date()).getTime();21 while((new Date()).getTime() - start < delay) {22 continue;23 }24 }25 beforeAll(async function (done) {26 console.debug("====>beforeAll start====");27 sleep(TIMEOUT);28 console.debug("====>beforeAll end====");29 done();30 });31 /*32 * @tc.number : ActsAccountSetGetExtraInfo_010033 * @tc.name : getAccountExtraInfo callback form34 * @tc.desc : Get additional information about an existing account35 */36 it('ActsAccountSetGetExtraInfo_0100', 0, async function (done) {37 console.debug("====>ActsAccountSetGetExtraInfo_0100 start====");38 var appAccountManager = account.createAppAccountManager();39 var extraInfoStr = "account_extrainfo_callback_first";40 console.debug("====>creat finish====");41 appAccountManager.addAccount("account_name_callback_first", extraInfoStr, (err)=>{42 console.debug("====>add account ActsAccountSetGetExtraInfo_0100 err:" + JSON.stringify(err));43 expect(err.code).assertEqual(0);44 appAccountManager.getAccountExtraInfo("account_name_callback_first", (err, data)=>{45 console.debug("====>getAccountExtraInfo 0100 err:" + JSON.stringify(err));46 console.debug("====>getAccountExtraInfo 0100 data:" + JSON.stringify(data));47 expect(err.code).assertEqual(0);48 expect(data).assertEqual(extraInfoStr);49 appAccountManager.deleteAccount("account_name_callback_first", (err)=>{50 console.debug("====>delete Account 0100 err:" + JSON.stringify(err));51 expect(err.code).assertEqual(0);52 console.debug("====>ActsAccountSetGetExtraInfo_0100 end====");53 done();54 });55 });56 });57 });58 /*59 * @tc.number : ActsAccountSetGetExtraInfo_020060 * @tc.name : getAccountExtraInfo promise form61 * @tc.desc : Get additional information about an existing account62 */63 it('ActsAccountSetGetExtraInfo_0200', 0, async function (done) {64 console.debug("====>ActsAccountSetGetExtraInfo_0200 start====");65 var appAccountManager = account.createAppAccountManager();66 var extraInfoStr = "account_extrainfo_promise_first";67 console.debug("====>creat finish====");68 console.debug("====>add account ActsAccountSetGetExtraInfo_0200 start====");69 await appAccountManager.addAccount("account_name_promise_first", extraInfoStr);70 try{71 var data = await appAccountManager.getAccountExtraInfo("account_name_promise_first");72 }73 catch(err){74 console.error("====>getAccountExtraInfo 0200 err:" + JSON.stringify(err));75 expect().assertFail();76 done();77 }78 console.debug("====>getAccountExtraInfo 0200 data:" + JSON.stringify(data));79 expect(data).assertEqual(extraInfoStr);80 console.debug("====>delete account ActsAccountSetGetExtraInfo_0200 start====");81 await appAccountManager.deleteAccount("account_name_promise_first");82 console.debug("====>ActsAccountSetGetExtraInfo_0200 end====");83 done();84 });85 /*86 * @tc.number : ActsAccountSetGetExtraInfo_030087 * @tc.name : getAccountExtraInfo callback form88 * @tc.desc : Get additional information about a non-existent account89 */90 it('ActsAccountSetGetExtraInfo_0300', 0, async function (done) {91 console.debug("====>ActsAccountSetGetExtraInfo_0300 start====");92 var appAccountManager = account.createAppAccountManager();93 console.debug("====>creat finish====");94 var notExistBundle = "account_name_callback_notexistbundle_second";95 appAccountManager.getAccountExtraInfo(notExistBundle, (err, data)=>{96 console.debug("====>getAccountExtraInfo 0300 err:" + JSON.stringify(err));97 expect(err.code != 0).assertEqual(true);98 console.debug("====>ActsAccountSetGetExtraInfo_0300 end====");99 done();100 });101 });102 /*103 * @tc.number : ActsAccountSetGetExtraInfo_0400104 * @tc.name : getAccountExtraInfo promise form105 * @tc.desc : Get additional information about a non-existent account106 */107 it('ActsAccountSetGetExtraInfo_0400', 0, async function (done) {108 console.debug("====>ActsAccountSetGetExtraInfo_0400 start====");109 var appAccountManager = account.createAppAccountManager();110 console.debug("====>creat finish====");111 var notExistBundle = "account_name_promise_notexistbundle_second";112 try{113 await appAccountManager.getAccountExtraInfo(notExistBundle);114 console.error("====>getAccountExtraInfo 0400 fail====");115 expect().assertFail();116 done();117 }118 catch(err){119 console.debug("====>getAccountExtraInfo 0400 err:" + JSON.stringify(err));120 expect(err.code != 0).assertEqual(true);121 console.debug("====>ActsAccountSetGetExtraInfo_0400 end====");122 done();123 }124 });125 /*126 * @tc.number : ActsAccountSetGetExtraInfo_0500127 * @tc.name : getAccountExtraInfo callback form128 * @tc.desc : Get additional information about deleted account129 */130 it('ActsAccountSetGetExtraInfo_0500', 0, async function (done) {131 console.debug("====>ActsAccountSetGetExtraInfo_0500 start====");132 var appAccountManager = account.createAppAccountManager();133 console.debug("====>creat finish====");134 appAccountManager.addAccount("account_name_callback_third", "account_extrainfo_callback_third", (err)=>{135 console.debug("====>add account ActsAccountSetGetExtraInfo_0500 err:" + JSON.stringify(err));136 expect(err.code).assertEqual(0);137 appAccountManager.deleteAccount("account_name_callback_third", (err)=>{138 console.debug("====>delete Account 0500 err:" + JSON.stringify(err));139 expect(err.code).assertEqual(0);140 appAccountManager.getAccountExtraInfo("account_name_callback_third", (err, data)=>{141 console.debug("====>getAccountExtraInfo 0500 err:" + JSON.stringify(err));142 console.debug("====>getAccountExtraInfo 0500 data:" + JSON.stringify(data));143 expect(err.code != 0).assertEqual(true);144 console.debug("====>ActsAccountSetGetExtraInfo_0500 end====");145 done();146 });147 });148 });149 });150 /*151 * @tc.number : ActsAccountSetGetExtraInfo_0600152 * @tc.name : getAccountExtraInfo promise form153 * @tc.desc : Get additional information about deleted account154 */155 it('ActsAccountSetGetExtraInfo_0600', 0, async function (done) {156 console.debug("====>ActsAccountSetGetExtraInfo_0600 start====");157 var appAccountManager = account.createAppAccountManager();158 console.debug("====>creat finish====");159 console.debug("====>add account ActsAccountSetGetExtraInfo_0600 start====");160 await appAccountManager.addAccount("account_name_promise_third", "account_extrainfo_promise_third");161 console.debug("====>delete account ActsAccountSetGetExtraInfo_0600 start====");162 await appAccountManager.deleteAccount("account_name_promise_third");163 try{164 await appAccountManager.getAccountExtraInfo("account_name_promise_third");165 console.error("====>getAccountExtraInfo 0600 fail====");166 expect().assertFail();167 done();168 }169 catch(err){170 console.debug("====>getAccountExtraInfo 0600 err:" + JSON.stringify(err));171 expect(err.code != 0).assertEqual(true);172 console.debug("====>ActsAccountSetGetExtraInfo_0600 end====");173 done();174 }175 });176 /*177 * @tc.number : ActsAccountSetGetExtraInfo_0700178 * @tc.name : getAccountExtraInfo callback form179 * @tc.desc : Get additional information that is not set180 */181 it('ActsAccountSetGetExtraInfo_0700', 0, async function (done) {182 console.debug("====>ActsAccountSetGetExtraInfo_0700 start====");183 var appAccountManager = account.createAppAccountManager();184 console.debug("====>creat finish====");185 appAccountManager.addAccount("account_name_callback_fourth", (err)=>{186 console.debug("====>add account ActsAccountSetGetExtraInfo_0700 err:" + JSON.stringify(err));187 expect(err.code).assertEqual(0);188 appAccountManager.getAccountExtraInfo("account_name_callback_fourth", (err, data)=>{189 console.debug("====>getAccountExtraInfo 0700 err:" + JSON.stringify(err));190 console.debug("====>getAccountExtraInfo 0700 data:" + JSON.stringify(data));191 expect(err.code).assertEqual(0);192 expect(data).assertEqual("");193 appAccountManager.deleteAccount("account_name_callback_fourth", (err)=>{194 console.debug("====>delete Account 0700 err:" + JSON.stringify(err));195 expect(err.code).assertEqual(0);196 console.debug("====>ActsAccountSetGetExtraInfo_0700 end====");197 done();198 });199 });200 });201 });202 /*203 * @tc.number : ActsAccountSetGetExtraInfo_0800204 * @tc.name : getAccountExtraInfo promise form205 * @tc.desc : Get additional information that is not set206 */207 it('ActsAccountSetGetExtraInfo_0800', 0, async function (done) {208 console.debug("====>ActsAccountSetGetExtraInfo_0800 start====");209 var appAccountManager = account.createAppAccountManager();210 console.debug("====>creat finish====");211 console.debug("====>add account ActsAccountSetGetExtraInfo_0800 start====");212 await appAccountManager.addAccount("account_name_promise_fourth");213 console.debug("====>getAccountExtraInfo ActsAccountSetGetExtraInfo_0800 start====");214 try{215 var data = await appAccountManager.getAccountExtraInfo("account_name_promise_fourth");216 }217 catch(err){218 console.error("====>getAccountExtraInfo 0800 err:" + JSON.stringify(err));219 expect().assertFail();220 done();221 }222 console.debug("====>getAccountExtraInfo 0800 data:" + JSON.stringify(data));223 expect(data).assertEqual("");224 console.debug("====>delete account ActsAccountSetGetExtraInfo_0800 start====");225 await appAccountManager.deleteAccount("account_name_promise_fourth");226 console.debug("====>ActsAccountSetGetExtraInfo_0800 end====");227 done();228 });229 /*230 * @tc.number : ActsAccountSetGetExtraInfo_0900231 * @tc.name : setAccountExtraInfo callback form232 * @tc.desc : Set account extension information that does not exist233 */234 it('ActsAccountSetGetExtraInfo_0900', 0, async function (done) {235 console.debug("====>ActsAccountSetGetExtraInfo_0900 start====");236 var appAccountManager = account.createAppAccountManager();237 console.debug("====>creat finish====");238 var notExtraAccount = "account_name_callback_fifth"239 appAccountManager.setAccountExtraInfo(notExtraAccount, "account_extrainfo_fifth", (err)=>{240 console.debug("====>setAccountExtraInfo 0900 err:" + JSON.stringify(err));241 expect(err.code != 0).assertEqual(true);242 console.debug("====>ActsAccountSetGetExtraInfo_0900 end====");243 done();244 });245 });246 /*247 * @tc.number : ActsAccountSetGetExtraInfo_1000248 * @tc.name : setAccountExtraInfo promise form249 * @tc.desc : Set account extension information that does not exist250 */251 it('ActsAccountSetGetExtraInfo_1000', 0, async function (done) {252 console.debug("====>ActsAccountSetGetExtraInfo_1000 start====");253 var appAccountManager = account.createAppAccountManager();254 console.debug("====>creat finish====");255 var notExtraAccount = "account_name_promise_fifth"256 try{257 await appAccountManager.setAccountExtraInfo(notExtraAccount, "account_extrainfo_fifth");258 console.error("====>setAccountExtraInfo fail ActsAccountSetGetExtraInfo_1000");259 expect().assertFail();260 done();261 }262 catch(err){263 console.debug("====>setAccountExtraInfo 1000 err:" + JSON.stringify(err));264 expect(err.code != 0).assertEqual(true);265 console.debug("====>ActsAccountSetGetExtraInfo_1000 end====");266 done();267 }268 });269 /*270 * @tc.number : ActsAccountSetGetExtraInfo_1100271 * @tc.name : setAccountExtraInfo getAccountExtraInfo callback form272 * @tc.desc : Get additional information that has been set273 */274 it('ActsAccountSetGetExtraInfo_1100', 0, async function (done) {275 console.debug("====>ActsAccountSetGetExtraInfo_1100 start====");276 var appAccountManager = account.createAppAccountManager();277 console.debug("====>creat finish====");278 appAccountManager.addAccount("account_name_callback_sixth", "account_extrainfo_callback_sixth",(err)=>{279 console.debug("====>add account ActsAccountSetGetExtraInfo_1100 err:" + JSON.stringify(err));280 expect(err.code).assertEqual(0);281 appAccountManager.setAccountExtraInfo("account_name_callback_sixth", "account_extra_sixth_twice", (err)=>{282 console.debug("====>setAccountExtraInfo 1100 err:" + JSON.stringify(err));283 expect(err.code).assertEqual(0);284 appAccountManager.getAccountExtraInfo("account_name_callback_sixth", (err, data)=>{285 console.debug("====>getAccountExtraInfo 1100 err:" + JSON.stringify(err));286 console.debug("====>getAccountExtraInfo 1100 data:" + JSON.stringify(data));287 expect(err.code).assertEqual(0);288 expect(data).assertEqual("account_extra_sixth_twice");289 appAccountManager.deleteAccount("account_name_callback_sixth", (err)=>{290 console.debug("====>delete Account 1100 err:" + JSON.stringify(err));291 expect(err.code).assertEqual(0);292 console.debug("====>ActsAccountSetGetExtraInfo_1100 end====");293 done();294 });295 });296 });297 });298 });299 /*300 * @tc.number : ActsAccountSetGetExtraInfo_1200301 * @tc.name : setAccountExtraInfo getAccountExtraInfo promise form302 * @tc.desc : Get additional information that has been set303 */304 it('ActsAccountSetGetExtraInfo_1200', 0, async function (done) {305 console.debug("====>ActsAccountSetGetExtraInfo_1200 start====");306 var appAccountManager = account.createAppAccountManager();307 console.debug("====>creat finish====");308 console.debug("====>add account ActsAccountSetGetExtraInfo_1200 start====");309 await appAccountManager.addAccount("account_name_promise_sixth", "account_extra_promise_sixth");310 console.debug("====>setAccountExtraInfo ActsAccountSetGetExtraInfo_1200 start====");311 await appAccountManager.setAccountExtraInfo("account_name_promise_sixth", "account_extra_sixth_twice");312 try{313 var data = await appAccountManager.getAccountExtraInfo("account_name_promise_sixth")314 }315 catch(err){316 console.error("====>getAccountExtraInfo 1200 err:" + JSON.stringify(err));317 expect().assertFail();318 done();319 }320 console.debug("====>getAccountExtraInfo 1200 data:" + JSON.stringify(data));321 expect(data).assertEqual("account_extra_sixth_twice");322 console.debug("====>delete account ActsAccountSetGetExtraInfo_1200 start====");323 await appAccountManager.deleteAccount("account_name_promise_sixth");324 console.debug("====>ActsAccountSetGetExtraInfo_1200 end====");325 done();326 });327 /*328 * @tc.number : ActsAccountSetGetExtraInfo_1300329 * @tc.name : setAccountExtraInfo getAccountExtraInfo callback form330 * @tc.desc : Get repeated setting of different additional information331 */332 it('ActsAccountSetGetExtraInfo_1300', 0, async function (done) {333 console.debug("====>ActsAccountSetGetExtraInfo_1300 start====");334 var appAccountManager = account.createAppAccountManager();335 console.debug("====>creat finish====");336 appAccountManager.addAccount("account_name_callback_seventh",(err)=>{337 console.debug("====>add account ActsAccountSetGetExtraInfo_1300 err:" + JSON.stringify(err));338 expect(err.code).assertEqual(0);339 appAccountManager.setAccountExtraInfo("account_name_callback_seventh", "callback_seventh", (err)=>{340 console.debug("====>setAccountExtraInfo 1300 first time err:" + JSON.stringify(err));341 expect(err.code).assertEqual(0);342 appAccountManager.setAccountExtraInfo("account_name_callback_seventh", "call_seventh_twice", (err)=>{343 console.debug("====>setAccountExtraInfo 1300 second time err:" + JSON.stringify(err));344 expect(err.code).assertEqual(0);345 appAccountManager.getAccountExtraInfo("account_name_callback_seventh", (err, data)=>{346 console.debug("====>getAccountExtraInfo 1300 err:" + JSON.stringify(err));347 console.debug("====>getAccountExtraInfo 1300 data:" + JSON.stringify(data));348 expect(err.code).assertEqual(0);349 expect(data).assertEqual("call_seventh_twice");350 appAccountManager.deleteAccount("account_name_callback_seventh", (err)=>{351 console.debug("====>delete Account 1300 err:" + JSON.stringify(err));352 });353 console.debug("====>ActsAccountSetGetExtraInfo_1300 end====");354 done();355 });356 });357 });358 });359 });360 /*361 * @tc.number : ActsAccountSetGetExtraInfo_1400362 * @tc.name : setAccountExtraInfo getAccountExtraInfo promise form363 * @tc.desc : Get repeated setting of different additional information364 */365 it('ActsAccountSetGetExtraInfo_1400', 0, async function (done) {366 console.debug("====>ActsAccountSetGetExtraInfo_1400 start====");367 var appAccountManager = account.createAppAccountManager();368 console.debug("====>creat finish====");369 console.debug("====>add account start ActsAccountSetGetExtraInfo_1400 start====");370 await appAccountManager.addAccount("extrapromise_seventh");371 console.debug("====>setAccountExtraInfo first time ActsAccountSetGetExtraInfo_1400====");372 await appAccountManager.setAccountExtraInfo("extrapromise_seventh", "extra_promise_seventh");373 try{374 var data = await appAccountManager.getAccountExtraInfo("extrapromise_seventh");375 }376 catch(err){377 console.error("====>getAccountExtraInfo first time 1400 err:" + JSON.stringify(err));378 expect().assertFail();379 done();380 }381 console.debug("====>getAccountExtraInfo 1400 first time data:" + JSON.stringify(data));382 expect(data).assertEqual("extra_promise_seventh");383 console.debug("====>setAccountExtraInfo second time ActsAccountSetGetExtraInfo_1400====");384 await appAccountManager.setAccountExtraInfo("extrapromise_seventh", "extra_promise_seventh_twice");385 try{386 var data = await appAccountManager.getAccountExtraInfo("extrapromise_seventh");387 }388 catch(err){389 console.error("====>getAccountExtraInfo 1400 err:" + JSON.stringify(err));390 expect().assertFail();391 done();392 }393 console.debug("====>getAccountExtraInfo 1400 data:" + JSON.stringify(data));394 expect(data).assertEqual("extra_promise_seventh_twice");395 console.debug("====>delete account ActsAccountSetGetExtraInfo_1400 start====");396 await appAccountManager.deleteAccount("extrapromise_seventh");397 console.debug("====>ActsAccountSetGetExtraInfo_1400 end====");398 done();399 });400 /*401 * @tc.number : ActsAccountSetGetExtraInfo_1500402 * @tc.name : setAccountExtraInfo getAccountExtraInfo callback form403 * @tc.desc : Get repeated setting of same additional information404 */405 it('ActsAccountSetGetExtraInfo_1500', 0, async function (done) {406 console.debug("====>ActsAccountSetGetExtraInfo_1500 start====");407 var appAccountManager = account.createAppAccountManager();408 console.debug("====>creat finish====");409 appAccountManager.addAccount("account_name_callback_eighth",(err)=>{410 console.debug("====>add account ActsAccountSetGetExtraInfo_1500 err:" + JSON.stringify(err));411 expect(err.code).assertEqual(0);412 appAccountManager.setAccountExtraInfo("account_name_callback_eighth", "extra_callback_eighth", (err)=>{413 console.debug("====>setAccountExtraInfo second time err:" + JSON.stringify(err));414 expect(err.code).assertEqual(0);415 appAccountManager.setAccountExtraInfo("account_name_callback_eighth", "extra_callback_eighth", (err)=>{416 console.debug("====>setAccountExtraInfo 1500 first time err:" + JSON.stringify(err));417 expect(err.code).assertEqual(0);418 appAccountManager.getAccountExtraInfo("account_name_callback_eighth", (err, data)=>{419 console.debug("====>getAccountExtraInfo 1500 err:" + JSON.stringify(err));420 console.debug("====>getAccountExtraInfo 1500 data:" + JSON.stringify(data));421 expect(err.code).assertEqual(0);422 expect(data).assertEqual("extra_callback_eighth");423 appAccountManager.deleteAccount("account_name_callback_eighth", (err)=>{424 console.debug("====>delete Account 1500 err:" + JSON.stringify(err));425 });426 console.debug("====>ActsAccountSetGetExtraInfo_1500 end====");427 done();428 });429 });430 });431 });432 });433 /*434 * @tc.number : ActsAccountSetGetExtraInfo_1600435 * @tc.name : setAccountExtraInfo getAccountExtraInfo promise form436 * @tc.desc : Get repeated setting of same additional information437 */438 it('ActsAccountSetGetExtraInfo_1600', 0, async function (done) {439 console.debug("====>ActsAccountSetGetExtraInfo_1600 start====");440 var appAccountManager = account.createAppAccountManager();441 console.debug("====>creat finish====");442 console.debug("====>add account ActsAccountSetGetExtraInfo_1600====");443 await appAccountManager.addAccount("account_name_promise_eighth");444 console.debug("====>setAccountExtraInfo first time start ActsAccountSetGetExtraInfo_1600====");445 try{446 await appAccountManager.setAccountExtraInfo("account_name_promise_eighth", "extra_promise_eighth");447 }448 catch(err){449 console.error("====>setAccountExtraInfo first time err:" + JSON.stringify(err));450 expect().assertFail();451 done();452 }453 try{454 var dataFir = await appAccountManager.getAccountExtraInfo("account_name_promise_eighth");455 }456 catch(err){457 console.error("====>getAccountExtraInfo first time 1600 err:" + JSON.stringify(err));458 expect().assertFail();459 done();460 }461 console.debug("====>getAccountExtraInfo first time 1600 dataFir:" + JSON.stringify(dataFir));462 expect(dataFir).assertEqual("extra_promise_eighth");463 console.debug("====>setAccountExtraInfo second time start ActsAccountSetGetExtraInfo_1600====");464 try{465 await appAccountManager.setAccountExtraInfo("account_name_promise_eighth", "extra_promise_eighth");466 }467 catch(err){468 console.error("====>setAccountExtraInfo second time err:" + JSON.stringify(err));469 expect().assertFail();470 done();471 }472 try{473 var dataSec = await appAccountManager.getAccountExtraInfo("account_name_promise_eighth");474 }475 catch(err){476 console.error("====>getAccountExtraInfo second time 1600 err:" + JSON.stringify(err));477 expect().assertFail();478 done();479 }480 console.debug("====>getAccountExtraInfo second time 1600 dataSec:" + JSON.stringify(dataSec));481 expect(dataSec).assertEqual("extra_promise_eighth");482 console.debug("====>delete account ActsAccountSetGetExtraInfo_1600 start====");483 await appAccountManager.deleteAccount("account_name_promise_eighth");484 console.debug("====>ActsAccountSetGetExtraInfo_1600 end====");485 done();486 });...
zipEntry.js
Source:zipEntry.js
1'use strict';2var StringReader = require('./stringReader');3var utils = require('./utils');4var CompressedObject = require('./compressedObject');5var jszipProto = require('./object');6var MADE_BY_DOS = 0x00;7var MADE_BY_UNIX = 0x03;8// class ZipEntry {{{9/**10 * An entry in the zip file.11 * @constructor12 * @param {Object} options Options of the current file.13 * @param {Object} loadOptions Options for loading the stream.14 */15function ZipEntry(options, loadOptions) {16 this.options = options;17 this.loadOptions = loadOptions;18}19ZipEntry.prototype = {20 /**21 * say if the file is encrypted.22 * @return {boolean} true if the file is encrypted, false otherwise.23 */24 isEncrypted: function() {25 // bit 1 is set26 return (this.bitFlag & 0x0001) === 0x0001;27 },28 /**29 * say if the file has utf-8 filename/comment.30 * @return {boolean} true if the filename/comment is in utf-8, false otherwise.31 */32 useUTF8: function() {33 // bit 11 is set34 return (this.bitFlag & 0x0800) === 0x0800;35 },36 /**37 * Prepare the function used to generate the compressed content from this ZipFile.38 * @param {DataReader} reader the reader to use.39 * @param {number} from the offset from where we should read the data.40 * @param {number} length the length of the data to read.41 * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).42 */43 prepareCompressedContent: function(reader, from, length) {44 return function() {45 var previousIndex = reader.index;46 reader.setIndex(from);47 var compressedFileData = reader.readData(length);48 reader.setIndex(previousIndex);49 return compressedFileData;50 };51 },52 /**53 * Prepare the function used to generate the uncompressed content from this ZipFile.54 * @param {DataReader} reader the reader to use.55 * @param {number} from the offset from where we should read the data.56 * @param {number} length the length of the data to read.57 * @param {JSZip.compression} compression the compression used on this file.58 * @param {number} uncompressedSize the uncompressed size to expect.59 * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).60 */61 prepareContent: function(reader, from, length, compression, uncompressedSize) {62 return function() {63 var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());64 var uncompressedFileData = compression.uncompress(compressedFileData);65 if (uncompressedFileData.length !== uncompressedSize) {66 throw new Error("Bug : uncompressed data size mismatch");67 }68 return uncompressedFileData;69 };70 },71 /**72 * Read the local part of a zip file and add the info in this object.73 * @param {DataReader} reader the reader to use.74 */75 readLocalPart: function(reader) {76 var compression, localExtraFieldsLength;77 // we already know everything from the central dir !78 // If the central dir data are false, we are doomed.79 // On the bright side, the local part is scary : zip64, data descriptors, both, etc.80 // The less data we get here, the more reliable this should be.81 // Let's skip the whole header and dash to the data !82 reader.skip(22);83 // in some zip created on windows, the filename stored in the central dir contains \ instead of /.84 // Strangely, the filename here is OK.85 // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes86 // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...87 // Search "unzip mismatching "local" filename continuing with "central" filename version" on88 // the internet.89 //90 // I think I see the logic here : the central directory is used to display91 // content and the local directory is used to extract the files. Mixing / and \92 // may be used to display \ to windows users and use / when extracting the files.93 // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/39494 this.fileNameLength = reader.readInt(2);95 localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir96 this.fileName = reader.readString(this.fileNameLength);97 reader.skip(localExtraFieldsLength);98 if (this.compressedSize == -1 || this.uncompressedSize == -1) {99 throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");100 }101 compression = utils.findCompression(this.compressionMethod);102 if (compression === null) { // no compression found103 throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")");104 }105 this.decompressed = new CompressedObject();106 this.decompressed.compressedSize = this.compressedSize;107 this.decompressed.uncompressedSize = this.uncompressedSize;108 this.decompressed.crc32 = this.crc32;109 this.decompressed.compressionMethod = this.compressionMethod;110 this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);111 this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);112 // we need to compute the crc32...113 if (this.loadOptions.checkCRC32) {114 this.decompressed = utils.transformTo("string", this.decompressed.getContent());115 if (jszipProto.crc32(this.decompressed) !== this.crc32) {116 throw new Error("Corrupted zip : CRC32 mismatch");117 }118 }119 },120 /**121 * Read the central part of a zip file and add the info in this object.122 * @param {DataReader} reader the reader to use.123 */124 readCentralPart: function(reader) {125 this.versionMadeBy = reader.readInt(2);126 this.versionNeeded = reader.readInt(2);127 this.bitFlag = reader.readInt(2);128 this.compressionMethod = reader.readString(2);129 this.date = reader.readDate();130 this.crc32 = reader.readInt(4);131 this.compressedSize = reader.readInt(4);132 this.uncompressedSize = reader.readInt(4);133 this.fileNameLength = reader.readInt(2);134 this.extraFieldsLength = reader.readInt(2);135 this.fileCommentLength = reader.readInt(2);136 this.diskNumberStart = reader.readInt(2);137 this.internalFileAttributes = reader.readInt(2);138 this.externalFileAttributes = reader.readInt(4);139 this.localHeaderOffset = reader.readInt(4);140 if (this.isEncrypted()) {141 throw new Error("Encrypted zip are not supported");142 }143 this.fileName = reader.readString(this.fileNameLength);144 this.readExtraFields(reader);145 this.parseZIP64ExtraField(reader);146 this.fileComment = reader.readString(this.fileCommentLength);147 },148 /**149 * Parse the external file attributes and get the unix/dos permissions.150 */151 processAttributes: function () {152 this.unixPermissions = null;153 this.dosPermissions = null;154 var madeBy = this.versionMadeBy >> 8;155 // Check if we have the DOS directory flag set.156 // We look for it in the DOS and UNIX permissions157 // but some unknown platform could set it as a compatibility flag.158 this.dir = this.externalFileAttributes & 0x0010 ? true : false;159 if(madeBy === MADE_BY_DOS) {160 // first 6 bits (0 to 5)161 this.dosPermissions = this.externalFileAttributes & 0x3F;162 }163 if(madeBy === MADE_BY_UNIX) {164 this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;165 // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);166 }167 // fail safe : if the name ends with a / it probably means a folder168 if (!this.dir && this.fileName.slice(-1) === '/') {169 this.dir = true;170 }171 },172 /**173 * Parse the ZIP64 extra field and merge the info in the current ZipEntry.174 * @param {DataReader} reader the reader to use.175 */176 parseZIP64ExtraField: function(reader) {177 if (!this.extraFields[0x0001]) {178 return;179 }180 // should be something, preparing the extra reader181 var extraReader = new StringReader(this.extraFields[0x0001].value);182 // I really hope that these 64bits integer can fit in 32 bits integer, because js183 // won't let us have more.184 if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {185 this.uncompressedSize = extraReader.readInt(8);186 }187 if (this.compressedSize === utils.MAX_VALUE_32BITS) {188 this.compressedSize = extraReader.readInt(8);189 }190 if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {191 this.localHeaderOffset = extraReader.readInt(8);192 }193 if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {194 this.diskNumberStart = extraReader.readInt(4);195 }196 },197 /**198 * Read the central part of a zip file and add the info in this object.199 * @param {DataReader} reader the reader to use.200 */201 readExtraFields: function(reader) {202 var start = reader.index,203 extraFieldId,204 extraFieldLength,205 extraFieldValue;206 this.extraFields = this.extraFields || {};207 while (reader.index < start + this.extraFieldsLength) {208 extraFieldId = reader.readInt(2);209 extraFieldLength = reader.readInt(2);210 extraFieldValue = reader.readString(extraFieldLength);211 this.extraFields[extraFieldId] = {212 id: extraFieldId,213 length: extraFieldLength,214 value: extraFieldValue215 };216 }217 },218 /**219 * Apply an UTF8 transformation if needed.220 */221 handleUTF8: function() {222 if (this.useUTF8()) {223 this.fileName = jszipProto.utf8decode(this.fileName);224 this.fileComment = jszipProto.utf8decode(this.fileComment);225 } else {226 var upath = this.findExtraFieldUnicodePath();227 if (upath !== null) {228 this.fileName = upath;229 }230 var ucomment = this.findExtraFieldUnicodeComment();231 if (ucomment !== null) {232 this.fileComment = ucomment;233 }234 }235 },236 /**237 * Find the unicode path declared in the extra field, if any.238 * @return {String} the unicode path, null otherwise.239 */240 findExtraFieldUnicodePath: function() {241 var upathField = this.extraFields[0x7075];242 if (upathField) {243 var extraReader = new StringReader(upathField.value);244 // wrong version245 if (extraReader.readInt(1) !== 1) {246 return null;247 }248 // the crc of the filename changed, this field is out of date.249 if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {250 return null;251 }252 return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));253 }254 return null;255 },256 /**257 * Find the unicode comment declared in the extra field, if any.258 * @return {String} the unicode comment, null otherwise.259 */260 findExtraFieldUnicodeComment: function() {261 var ucommentField = this.extraFields[0x6375];262 if (ucommentField) {263 var extraReader = new StringReader(ucommentField.value);264 // wrong version265 if (extraReader.readInt(1) !== 1) {266 return null;267 }268 // the crc of the comment changed, this field is out of date.269 if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {270 return null;271 }272 return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));273 }274 return null;275 }276};...
extraQuestions.js
Source:extraQuestions.js
1const helpers = require('./helpers');2const Analytics = require('./analytics');3const Goodbye = require('./goodbye');4const translations = helpers.translations.Extra;5const CALLBACK_KEY_PREFIX = 'USER_FEEDBACK_CONTINUE_EXTRA_';6// replies's translation keys7const REPLIES = {8 START: [9 'start_yes',10 'start_no'11 ],12 ACTIVITY_LIGHT: [13 'activity_light_0_4',14 'activity_light_4_8',15 'activity_light_8_plus',16 ],17 ACTIVITY_INTENSE: [18 'activity_intense_0_2',19 'activity_intense_2_4',20 'activity_intense_4_plus'21 ],22 STRESSED: [23 'stressed_1',24 'stressed_2',25 'stressed_3',26 'stressed_4',27 'stressed_5'28 ],29 CAREGIVER: [30 'caregiver_yes',31 'caregiver_no'32 ],33}34async function StartExtraQuestion(context) {35 await context.setState({36 nextAction: 'CONTINUE_EXTRA'37 });38 await sendTextWithReplies(context, translations.question_continue_extra, REPLIES.START);39}40async function AskActivityLight(context) {41 await context.setState({42 nextAction: 'EXTRA_ASK_ACTIVITY_LIGHT'43 });44 await helpers.sendText(context, translations.question_activity);45 await sendTextWithReplies(context, translations.question_activity_light, REPLIES.ACTIVITY_LIGHT);46}47async function AskActivityIntense(context) {48 await context.setState({49 nextAction: 'EXTRA_ASK_ACTIVITY_INTENSE'50 });51 await sendTextWithReplies(context, translations.question_activity_intense, REPLIES.ACTIVITY_INTENSE);52}53async function AskIfStressed(context) {54 await context.setState({55 nextAction: 'EXTRA_ASK_STRESSED'56 });57 await sendTextWithReplies(context, translations.question_stressed, REPLIES.STRESSED);58}59async function AskIfCaregiver(context) {60 await context.setState({61 nextAction: 'EXTRA_ASK_CAREGIVER'62 });63 await sendTextWithReplies(context, translations.question_caregiver, REPLIES.CAREGIVER);64}65async function FinishQuestions(context) {66 await context.setState({67 nextAction: 'NONE'68 });69 await helpers.sendText(context, translations.thank_you);70 await Goodbye.Goodbye(context);71}72async function HandleContinueExtra(context) {73 const callbackKey = context.event.payload || lookupCallbackKey(context.event.text, REPLIES.START);74 if (callbackKey === 'USER_FEEDBACK_CONTINUE_EXTRA_START_NO') {75 await helpers.sendText(context, translations.start_no_response);76 await Goodbye.Goodbye(context);77 return;78 }79 if (callbackKey === 'USER_FEEDBACK_CONTINUE_EXTRA_START_YES') {80 await helpers.sendText(context, translations.start_yes_response);81 await AskExtraQuestions(context);82 }83}84async function AskExtraQuestions(context) {85 const performedExtraQuestions = extractPerformedExtraQuestions(context);86 if (!performedExtraQuestions.includes('activity_light')) {87 await AskActivityLight(context);88 } else if (!performedExtraQuestions.includes('activity_intense')) {89 await AskActivityIntense(context);90 } else if (!performedExtraQuestions.includes('stressed')) {91 await AskIfStressed(context);92 } else if (!performedExtraQuestions.includes('caregiver')) {93 await AskIfCaregiver(context);94 } else {95 await FinishQuestions(context);96 }97}98async function HandleExtraReply(context) {99 const nextAction = context.state.nextAction || '';100 if (!nextAction.includes('EXTRA_ASK_')) {101 return;102 }103 const questionKey = nextAction.replace('EXTRA_ASK_', '');104 const callbackKey = context.event.payload || lookupCallbackKey(context.event.text, REPLIES[questionKey]);105 if (!callbackKey) {106 await helpers.sendText(context, translations.do_not_understand);107 await AskExtraQuestions(context);108 return;109 }110 await Analytics.SaveEvent(context, callbackKey);111 const previousAnswers = extractExtraQuestionsAnswers(context);112 const currentAnswer = callbackKey.toLowerCase();113 if (previousAnswers.includes('activity_light_0_4') && currentAnswer.includes('activity_intense_0_2')) {114 await helpers.sendText(context, translations.advise_low_activity);115 } else if (previousAnswers.includes('activity_light_8_plus') && currentAnswer.includes('activity_intense_4_plus')) {116 await helpers.sendText(context, translations.advise_high_activity);117 } else if (currentAnswer.includes('activity_intense')) {118 await helpers.sendText(context, translations.advise_moderate_activity);119 }120 if (currentAnswer.includes('stressed_3') || currentAnswer.includes('stressed_4') || currentAnswer.includes('stressed_5')) {121 await helpers.sendText(context, translations.advise_stress_high);122 } else if (currentAnswer.includes('stressed_1') || currentAnswer.includes('stressed_2')) {123 await helpers.sendText(context, translations.advise_stress_low);124 }125 if (currentAnswer.includes('caregiver_yes')) {126 await helpers.typing(context, 1200);127 const url = 'https://www.hopkinsmedicine.org/health/conditions-and-diseases/coronavirus/coronavirus-caregiving-for-the-elderly';128 const urlTitle = 'Read more here';129 if (context.platform === 'telegram') {130 await context.sendText(translations.advise_caregiver_yes, {131 replyMarkup: {132 inlineKeyboard: [[{133 text: urlTitle,134 url: url,135 }]]136 }137 });138 } else {139 await context.sendButtonTemplate(translations.advise_caregiver_yes, [{140 type: 'web_url',141 url: url,142 title: urlTitle,143 }]);144 }145 await helpers.typingOff(context);146 } else if (currentAnswer.includes('caregiver_no')) {147 await helpers.sendText(context, translations.advise_caregiver_no);148 }149 await AskExtraQuestions(context);150}151function extractPerformedExtraQuestions(context) {152 const answers = extractExtraQuestionsAnswers(context);153 const extraQuestions = [154 'activity_light',155 'activity_intense',156 'stressed',157 'caregiver'158 ];159 return extraQuestions.filter(question => {160 let isIncluded = false;161 answers.forEach(element => {162 isIncluded = isIncluded || element.includes(question);163 });164 return isIncluded;165 })166}167function extractExtraQuestionsAnswers(context) {168 return helpers.extractEvents(context, 'USER_FEEDBACK_CONTINUE_EXTRA');169}170async function sendTextWithReplies(context, text, repliesKeyArray) {171 return await helpers.sendTextWithReplies(context, text, repliesKeyArray, translations, CALLBACK_KEY_PREFIX);172}173function lookupCallbackKey(textValue, translationKeys) {174 return helpers.lookupCallbackKey(textValue, translations, translationKeys, CALLBACK_KEY_PREFIX);175}176module.exports = {177 StartExtraQuestion,178 HandleContinueExtra,179 HandleExtraReply,...
index.js
Source:index.js
1import { default as fieldTypes, tableBindType, isBindTableType } from './fieldTypes'2/*3 * è·åcolumnä¸æ¾ç¤ºçfiledValue4 */5function getFieldValue(value, field = {}, record, fn) {6 let type = field.type || (field.enums && 'enum') || (field.table && field.table.enums && 'enum')7 type = Object.prototype.hasOwnProperty.call(fieldTypes, type) ? type : 'normal'8 return fieldTypes[type](value, field, record, fn)9}10/*11 * è·åè¡¨æ ¼columnæ°ç»12 * 示ä¾:13 * const columns = getColumns(fields,['name','author'],{ name: { render: ()=>{} }}).values();14 * const columns = getColumns(fields).excludes(['id','desc']).values();15 * const columns = getColumns(fields).pick(['name','author','openTime']).enhance({name:{ render: ()=>{} }}).values();16 * @param originField åå§fields17 * @param fieldKeys éè¦å
å«çå段keys18 * @param extraFields æ©å±çfields19 * @result é¾å¼åæ³ï¼è¿åé¾å¼å¯¹è±¡(å
å«pick,excludes,enhance,valuesæ¹æ³), éè¦è°ç¨valuesè¿åæç»çæ°æ®20 */21function getColumns(fields, fieldKeys, extraFields, fn) {22 const chain = {}23 let columns = []24 const transform = _fields => {25 return _fields.map(field => {26 let { dataIndex, title, key, name, render, ...others } = field27 if (!render) {28 render = (value, record) => {29 return getFieldValue(value, field, record, fn)30 }31 }32 return {33 dataIndex: key || dataIndex,34 title: name || title,35 render,36 ...others,37 }38 })39 }40 const pick = _fieldKeys => {41 _fieldKeys = [].concat(_fieldKeys)42 columns = _fieldKeys.map(fieldKey => {43 let column44 for (let i in columns) {45 const item = fields[i]46 const hasRender = !!item.render47 if (fieldKey === (item.key || item.dataIndex)) {48 // å¦æfieldKeyä¸åå¨ï¼åå建textç±»åçcolumn49 column = {50 dataIndex: fieldKey,51 title: item.name || fieldKey,52 render: hasRender53 ? item.render54 : (value, record) => {55 return getFieldValue(value, item, record, fn)56 },57 }58 }59 }60 return column61 })62 return chain63 }64 const excludes = _fieldKeys => {65 _fieldKeys = [].concat(_fieldKeys)66 columns = columns.filter(column => {67 for (let i in _fieldKeys) {68 const item = _fieldKeys[i]69 if (item === column.dataIndex) {70 return false71 }72 }73 return true74 })75 return chain76 }77 const enhance = _extraColumns => {78 if (!Array.isArray(_extraColumns)) {79 _extraColumns = Object.keys(_extraColumns).map(key => {80 return Object.assign(_extraColumns[key], {81 key,82 })83 })84 }85 _extraColumns.forEach(extraColumn => {86 const { dataIndex, title, key, name, ...others } = extraColumn87 extraColumn = {88 dataIndex: key || dataIndex,89 title: name || title,90 ...others,91 }92 let column93 for (let i in columns) {94 const item = columns[i]95 if (item === undefined) {96 column = extraColumn.dataIndex97 } else if (item.dataIndex === extraColumn.dataIndex) {98 column = item.dataIndex99 }100 }101 if (column) {102 Object.assign(column, extraColumn)103 } else {104 columns.push(extraColumn)105 }106 })107 return chain108 }109 const values = () => {110 return columns111 }112 columns = transform(fields)113 if (fieldKeys) {114 pick(fieldKeys)115 }116 if (extraFields) {117 enhance(extraFields)118 }119 return Object.assign(chain, {120 pick,121 excludes,122 enhance,123 values,124 })125}126export default {127 isBindTableType,128 fieldTypes,129 tableBindType,130 getFieldValue,131 getColumns,...
bubble.js
Source:bubble.js
1(function() {2 var extra = {};3 c3.chart.internal.fn.additionalConfig = {4 data_pairs: [],5 };6 c3.chart.internal.fn.beforeInit = function (config) {7 var that = this;8 // update internals only when chart type is "bubble"9 if (config.data.type !== 'bubble') {10 return;11 }12 // Set extra to ba able to be used in other part13 this.extra = extra;14 extra.getKey = function (x, y) {15 return x + '::' + y;16 };17 this.config.data_type = 'scatter';18 this.config.axis_x_padding = 0;19 this.config.axis_y_padding = 0;20 this.config.axis_x_tick_centered = true;21 this.config.axis_x_tick_format = function (d) {22 return extra.names[d];23 };24 this.config.axis_y_tick_format = function (d) {25 return extra.names[d];26 };27 if (!config.color || !config.color.pattern) {28 this.config.color_pattern = ['#1f77b4'];29 }30 this.config.point_r = function (d) {31 var names = extra.names, values = extra.values, base_length = extra.base_length,32 x = names[d.x], y = d.id,33 key = extra.getKey(x, y), value = !values[key] ? 0 : values[key],34 max, max_r, max_area, a, area, r;35 if (!base_length) {36 base_length = extra.base_length = d3.min([37 that.svg.select('.c3-axis.c3-axis-y path').node().getTotalLength(),38 that.svg.select('.c3-axis.c3-axis-x path').node().getTotalLength(),39 ]);40 }41 max = d3.max(Object.keys(values).map(function (key) { return values[key]; }));42 max_r = (base_length / (names.length * 2));43 max_area = max_r * max_r * Math.PI;44 a = max_area / max;45 area = value * a;46 r = Math.sqrt(area / Math.PI);47 return r;48 };49 this.config.point_sensitivity = 25;50 this.config.point_focus_expand_enabled = false;51 this.config.legend_show = false;52 if (!config.tooltip || !config.tooltip.contents) {53 this.config.tooltip_contents = function (d, defaultTitleFormat, defaultValueFormat, color) {54 var x = extra.names[d[0].x], y = d[0].name, v = extra.values[extra.getKey(x, y)], text;55 text = "<table class='" + this.CLASS.tooltip + "'>";56 text += "<tr><th colspan='2'>" + x + " / " + y + "</th></tr>";57 text += "<tr><td class='value'>" + (!v ? 0 : v) + "</td></tr>";58 text += "</table>";59 return text;60 };61 }62 // construct bubble chart data and setup config based on the values63 var xs = this.config.data_pairs.map(function (pair) { return pair.x; }),64 ys = this.config.data_pairs.map(function (pair) { return pair.y; });65 extra.names = d3.set(xs.concat(ys)).values().sort();66 this.config.axis_y_tick_values = extra.names.map(function (name, i) { return i; });67 var data_xs = {};68 extra.names.forEach(function (name) {69 data_xs[name] = name + '_x';70 });71 var data_columns_xs = Object.keys(data_xs).map(function (key) {72 return [data_xs[key]].concat(extra.names.map(function (name, i) { return i; }));73 });74 var data_columns_values = extra.names.map(function (name, i) {75 return [name].concat(extra.names.map(function (name) { return i; }));76 });77 this.config.data_xs = data_xs;78 this.config.data_columns = data_columns_xs.concat(data_columns_values);79 var values = {};80 this.config.data_pairs.forEach(function (pair) {81 if (!pair.x || !pair.y) {82 throw "x and y are required in data.";83 }84 values[extra.getKey(pair.x, pair.y)] = pair.value;85 });86 extra.values = values;87 this.config.axis_x_min = this.config.axis_y_min = -0.5;88 this.config.axis_x_max = this.config.axis_y_max = extra.names.length - 0.5;89 };...
addExtraPriceInfo.js
Source:addExtraPriceInfo.js
1'use strict'2const chai = require('chai')3const addExtraPrice = require('../../addExtraPriceInfo')4const context = {5 config: {6 extraPriceInfo: 'extra info property'7 }8}9const productsWithExtraPrice = [10 {11 id: '123',12 properties: [13 {14 label: 'extra info property',15 value: '120 Kapsen'16 }17 ]18 }19]20const productsWithoutExtraPrice = [21 {22 id: '123',23 properties: [24 {25 label: 'not extra info property',26 value: 'unneeded value'27 }28 ]29 }30]31const productsAfterExtraPriceAdded = [32 {33 id: '123',34 properties: [35 {36 label: 'extra info property',37 value: '120 Kapsen'38 }39 ],40 flags: {41 extraPriceInfo: '120 Kapsen'42 }43 }44]45const productsAfterNoExtraPriceAdded = [46 {47 id: '123',48 properties: [49 {50 label: 'not extra info property',51 value: 'unneeded value'52 }53 ],54 flags: {55 extraPriceInfo: null56 }57 }58]59describe('addExtraPrice', () => {60 it('should have extra price', async () => {61 const results = await addExtraPrice(context, {products: productsWithExtraPrice})62 chai.assert.deepEqual(results, {products: productsAfterExtraPriceAdded})63 })64 it('should not have extra price', async () => {65 const results = await addExtraPrice(context, {products: productsWithoutExtraPrice})66 chai.assert.deepEqual(results, {products: productsAfterNoExtraPriceAdded})67 })...
product.js
Source:product.js
1import { createSelector } from 'reselect';2import {3 getProductById,4 getProduct,5} from '@shopgate/pwa-common-commerce/product/selectors/product';6/**7 * Gets the extra price info from product8 * @param {Object} product Product data.9 * @return {string|null}10 */11const findExtraPriceInfo = (product) => {12 if (!product) {13 return null;14 }15 if (product.flags && product.flags.extraPriceInfo) {16 return product.flags.extraPriceInfo;17 }18 if (product.productData19 && product.productData.flags20 && product.productData.flags.extraPriceInfo21 ) {22 return product.productData.flags.extraPriceInfo;23 }24 return null;25};26/**27 * Gets extra price info by product id28 * @return {Object}29 */30export const getExtraPriceInfoByProductId = createSelector(31 getProductById,32 product => findExtraPriceInfo(product)33);34/**35 * Gets price of product by product id36 * @return {Object}37 */38export const getProductPriceById = createSelector(39 getProductById,40 product => product.productData.price41);42/**43 * Gets extra price info of current product44 * @return {Object}45 */46export const getCurrentProductExtraPriceInfo = createSelector(47 getProduct,48 product => findExtraPriceInfo(product)...
extra.js
Source:extra.js
1const assert = require('assert')2const Extra = require('../extra')3describe('Extra', () => {4 describe('_orderBy ascending', () => {5 const extra = new Extra({ '_orderBy': 'id' })6 it('has correct string', () => {7 assert.ok(extra.string == 'ORDER BY "id" ASC')8 })9 })10 describe('_orderBy descending', () => {11 const extra = new Extra({ '_orderBy': '-id' })12 it('has correct string', () => {13 assert.ok(extra.string == 'ORDER BY "id" DESC')14 })15 })16 describe('_offset only is not allowed', () => {17 const extra = new Extra({ '_offset': 10 })18 it('has correct string', () => {19 assert.ok(extra.string == '')20 })21 })22 describe('_limit without offset', () => {23 const extra = new Extra({ '_limit': 10 })24 it('has correct string with OFFSET 0', () => {25 assert.ok(extra.string == 'LIMIT 10 OFFSET 0')26 })27 })28 describe('_limit with _offset', () => {29 const extra = new Extra({ '_limit': 10, '_offset': 10 })30 it('has correct string', () => {31 assert.ok(extra.string == 'LIMIT 10 OFFSET 10')32 })33 })...
Using AI Code Generation
1Cypress.Commands.add("login", (email, password) => {2 cy.get('input[name="email"]').type(email);3 cy.get('input[name="password"]').type(password);4 cy.get('button[type="submit"]').click();5});6Cypress.Commands.add("logout", () => {7 cy.get('button[aria-label="logout"]').click();8});9Cypress.Commands.add("getBySel", (selector, ...args) => {10 return cy.get(`[data-test=${selector}]`, ...args);11});12Cypress.Commands.add("getBySelLike", (selector, ...args) => {13 return cy.get(`[data-test*=${selector}]`, ...args);14});15Cypress.Commands.add("loginByForm", (username, password) => {16 cy.getBySel("login-form").within(() => {17 cy.getBySel("username").type(username);18 cy.getBySel("password").type(password);19 cy.root().submit();20 });21});22Cypress.Commands.add("loginByForm", (username, password) => {23 cy.getBySel("login-form").within(() => {24 cy.getBySel("username").type(username);25 cy.getBySel("password").type(password);26 cy.root().submit();27 });28});29Cypress.Commands.add("loginByApi", (username, password) => {30 cy.request({31 body: {32 }33 }).then(response => {34 window.localStorage.setItem("token", response.body.token);35 });36});37Cypress.Commands.add("loginByApi", (username, password) => {38 cy.request({39 body: {40 }41 }).then(response => {42 window.localStorage.setItem("token", response.body.token);43 });44});45Cypress.Commands.add("loginByApi", (username, password) => {46 cy.request({47 body: {
Using AI Code Generation
1require('cypress-xpath');2describe('My First Test', function() {3 it('Does not do much!', function() {4 cy.contains('type').click()5 cy.url().should('include', '/commands/actions')6 cy.get('.action-email')7 .type('
Using AI Code Generation
1require('cypress-xpath')2describe('My First Test', function() {3 it('Does not do much!', function() {4 cy.get('input[type="text"]').type('test')5 cy.get('input[type="password"]').type('test')6 cy.get('button').click()7 })8})9describe('My First Test', function() {10 it('Does not do much!', function() {11 cy.get('input[type="text"]').type('test')12 cy.get('input[type="password"]').type('test')13 cy.get('button').click()14 })15})16cy.get('#id').should('be.visible')17cy.get('.class').should('be.visible')18cy.get('p').contains('test').should('be.visible')19cy.get('#id').should('be.visible')20cy.get('.class').should('be.visible')
Using AI Code Generation
1import 'cypress-file-upload';2import 'cypress-xpath';3require('cypress-downloadfile/lib/downloadFileCommand');4require('cypress-xpath');5import 'cypress-file-upload';6import 'cypress-xpath';7describe('Login', function() {8 it('Login', function() {9 cy.get('#user-name').type('standard_user')10 cy.get('#password').type('secret_sauce')11 cy.get('#login-button').click()12 })13})14describe('Add to Cart', function() {15 it('Add to Cart', function() {16 cy.get('[data-test=add-to-cart-sauce-labs-backpack]').click()17 cy.get('[data-test=add-to-cart-sauce-labs-bike-light]').click()18 cy.get('[data-test=add-to-cart-sauce-labs-bolt-t-shirt]').click()19 cy.get('[data-test=add-to-cart-sauce-labs-fleece-jacket]').click()20 cy.get('[data-test=add-to-cart-sauce-labs-onesie]').click()21 cy.get('[data-test=add-to-cart-test.allthethings()-t-shirt-(red)]').click()22 })23})24describe('Remove from Cart', function() {25 it('Remove from Cart', function() {26 cy.get('[data-test=remove-sauce-labs-backpack]').click()27 cy.get('[data-test=remove-sauce-labs-bike-light]').click()28 cy.get('[data-test=remove-sauce-labs-bolt-t-shirt]').click()29 cy.get('[data-test=remove-sauce-labs-fleece-jacket]').click()30 cy.get('[data-test=remove-sauce-labs-onesie]').click()31 cy.get('[data-test=remove-test.allthethings()-t-shirt-(red)]').click()32 })33})34describe('Checkout', function() {35 it('Checkout', function() {36 cy.get('[data-test=checkout]').click()37 cy.get('#first-name').type('John')38 cy.get('#last-name').type('Doe')39 cy.get('#postal-code').type('12345')40 cy.get('[data
Using AI Code Generation
1require('cypress-xpath')2import chai from 'chai';3const expect = chai.expect;4describe('My First Test', function() {5 it('Does not do much!', function() {6 expect(true).to.equal(true)7 })8})9import chai from 'chai';10const expect = chai.expect;11describe('My First Test', function() {12 it('Does not do much!', function() {13 expect(true).to.equal(true)14 })15})16import chai from 'chai';17const expect = chai.expect;18describe('My First Test', function() {19 it('Does not do much!', function() {20 expect(true).to.equal(true)21 })22})23import chai from 'chai';24const expect = chai.expect;25describe('My First Test', function() {26 it('Does not do much!', function() {27 expect(true).to.equal(true)28 })29})30import chai from 'chai';31const expect = chai.expect;32describe('My First Test', function() {33 it('Does not do much!', function() {34 expect(true).to.equal(true)35 })36})37import chai from 'chai';38const expect = chai.expect;39describe('My First Test', function() {40 it('Does not do much!', function() {41 expect(true).to.equal(true)42 })43})44import chai from 'chai';45const expect = chai.expect;46describe('My First Test', function() {47 it('Does not do much!', function() {48 expect(true).to.equal(true)49 })50})51import chai from 'chai';52const expect = chai.expect;53describe('My First Test', function() {54 it('Does not do much!', function() {55 expect(true).to.equal(true)56 })57})58import chai from 'chai';59const expect = chai.expect;60describe('My First Test', function() {61 it('Does not do much!', function() {62 expect(true).to.equal(true)63 })64})65import chai from 'chai';66const expect = chai.expect;67describe('My
Using AI Code Generation
1require('cypress-xpath')2describe('Test', function() {3 it('Test', function() {4 cy.xpath('')5 cy.xpath('')6 cy.xpath('')7 })8})9Hi, I am trying to use the extra method of Cypress in my project, but I am getting the following error: "CypressError: cy.xpath() is not a function". I have already installed the package "cypress-xpath" and the "support/index.js" file is configured with the following code:
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!