Best JavaScript code snippet using cypress
index.js
Source:index.js
1/* eslint-disable no-undef */2/**3 * Created by 001264 on 2019/9/9.4 */5import Vue from 'vue'6import { mapState } from 'vuex'7import { envConfig } from 'src/common/js/env.config'8import Location from 'fcbox/utils/location'9import ajax from 'fcbox/utils/http/ajax'10import COS from 'cos-js-sdk-v5'11import PublicFunc from '../func/public_func'12import FormatFunc from '../func/format_style'13import PopDrag from '../func/pop_drag'14import FcButton from 'fcbox/form/button'15import FcInput from 'fcbox/form/input'16import FcEditor from 'fcbox/form/editor'17import FcSingleSelector from 'fcbox/form/selector/single'18import FcSlider from 'fcbox/form/slider'19import FcSingleUpload from 'fcbox/upload/qq'20import FcTextarea from 'fcbox/form/textarea'21import FcRadioTab from 'fcbox/form/radio_tab'22import OrderSetter from 'fcbox/order_setter'23import ParamSetter from '../param_setter'24import FcFramePlayer from 'fcbox/player/frame'25import PlayerStatusBar from 'fcbox/player/player_status_bar'26import FcPreImage from 'fcbox/image/pre'27import FcFitImage from 'fcbox/image/fit'28import FcPop from 'fcbox/pop/pop'29import { ColorPicker } from 'element-ui'30// modules31import MImages from '../modules/images'32import MMenus from '../modules/menus'33import MGoods from '../modules/goods'34import MTab from '../modules/tab'35import MGroup from '../modules/group'36import MPop from '../modules/pop'37import EImage from '../elements/image'38import EText from '../elements/text'39import EIcon from '../elements/icon'40import EBusiness from '../elements/business'41Vue.use(MImages)42Vue.use(MMenus)43Vue.use(MGoods)44Vue.use(MTab)45Vue.use(MGroup)46Vue.use(MPop)47Vue.use(EImage)48Vue.use(EText)49Vue.use(EIcon)50Vue.use(EBusiness)51Vue.use(FcButton)52Vue.use(FcInput)53Vue.use(FcEditor)54Vue.use(FcSingleSelector)55Vue.use(FcSlider)56Vue.use(FcSingleUpload)57Vue.use(FcTextarea)58Vue.use(FcRadioTab)59Vue.use(OrderSetter)60Vue.use(ParamSetter)61Vue.use(FcFramePlayer)62Vue.use(PlayerStatusBar)63Vue.use(FcPreImage)64Vue.use(FcFitImage)65Vue.use(FcPop)66Vue.use(ColorPicker)67const Index = {68 name: 'Index',69 data () {70 return {71 envConfig,72 themeTabValue: 'module', // module -> 模å page -> 页é¢73 setContentType: 'page', // page -> é¡µé¢ pop -> å¼¹çª global -> å
¨å±è®¾ç½®74 popContentType: 'set', // set -> 设置 element -> å
ç´ 75 bodyStyle: {},76 pageStyle: {},77 color2: '#ff0000',78 contextmenuParam: {79 show: false,80 style: {},81 setType: ''82 },83 previewPopParam: {84 show: false,85 maskClose: true86 },87 showAhead: false,88 showUndo: false,89 popRandKey: Math.random(),90 getPopTitle () {91 let title92 let setConfig = this.setConfig93 switch (setConfig.setType) {94 case 'module':95 title = '模å设置'96 if (this.popContentType == 'element') {97 title = 'æå
¥å
ç´ '98 }99 break100 case 'page':101 title = '页é¢è®¾ç½®'102 break103 case 'pop':104 title = 'å¼¹çªè®¾ç½®'105 break106 case 'element':107 title = 'å
ç´ è®¾ç½®'108 break109 }110 return title111 }112 }113 },114 computed: mapState({115 setConfig: state => state.setConfig,116 contentConfig: state => state.contentConfig117 }),118 created () {119 },120 mounted () {121 if (sessionStorage.getItem('configContentCatch')) {122 this.$store.state.contentConfig = JSON.parse(sessionStorage.getItem('configContentCatch'))123 }124 this.bodyClickEventInit()125 this.refreshPageList()126 this.refreshPopList()127 this.refreshContent()128 this.keyActionInit()129 // 设置弹çªç§»å¨130 new PopDrag({131 eDomId: 'setterPopTitle',132 mDomId: 'setterPop'133 })134 new PopDrag({135 eDomId: 'elementPopTitle',136 mDomId: 'elementPop'137 })138 },139 methods: Object.assign({140 preview () {141 localStorage.setItem('previewData', JSON.stringify(this.trimObjBlank(this.contentConfig)))142 this.previewPopParam.show = true143 },144 save () {145 if (!this.contentConfig.body.title) {146 window.fc.Dialog.show({ text: '请填åæ é¢' })147 return false148 }149 let fileName = this.getRandId() + '.json'150 let path = 'advice'151 ajax.get({152 url: this.$store.state.config.api.op.customerServiceCenter.upSign,153 data: {154 fileName,155 directory: path156 }157 }).then((res) => {158 res = JSON.parse(res)159 if (res && res.data) {160 let d = res.data161 let date = new Date()162 let month = date.getMonth() + 1163 month = month < 10 ? '0' + month : month164 let year = date.getFullYear().toString()165 var cos = new COS({166 getAuthorization: (options, callback) => {167 callback(d.sign)168 }169 })170 cos.putObject({171 Bucket: d.bucket + '-' + d.appId,172 Region: d.region,173 Key: path + '/' + year + month + '/' + fileName,174 Body: JSON.stringify(this.trimObjBlank(this.contentConfig))175 }, (err, data) => {176 if (err || !data || data.statusCode != 200) {177 window.fc.Dialog.show({ text: err })178 } else {179 var url = 'http://' + d.bucket + '-' + d.appId + '.file.myqcloud.com/' + path + '/' + year + month + '/' + fileName180 this.saveContent(url)181 // console.log(url)182 }183 })184 }185 })186 },187 saveContent (adviceUrl) {188 let { contentConfig } = this189 let postData = {190 showType: contentConfig.body.showType || 'å¸å',191 adviceTitle: contentConfig.body.title || '',192 adviceRemark: contentConfig.body.keyword || '',193 shareImage: contentConfig.body.shareImage || '',194 adviceSubheading: contentConfig.body.adviceSubheading || '',195 adviceUrl,196 directionUrl: ''197 }198 let postParam = {199 url: this.$store.state.config.api.op.customerServiceCenter.addAdviceFeedback,200 data: postData201 }202 if (Location.queryParams['id']) {203 postParam.url = this.$store.state.config.api.op.customerServiceCenter.updateAdviceFeedback204 postParam.data.id = Location.queryParams['id']205 }206 ajax.post(postParam).then((res) => {207 res = JSON.parse(res)208 window.fc.Dialog.show({209 text: res.msg,210 confirmCallback: () => {211 history.go(-1)212 }213 })214 })215 },216 // å
³é设置弹çª217 closeSetterPop () {218 this.setConfig.showSetterPop = false219 },220 closeElementPop () {221 this.setConfig.showElementPop = false222 },223 // åæ¢æ¨¡åã页é¢æ¨¡çè§å¾224 changeThemeTab (value) {225 this.themeTabValue = value226 },227 // 模åå表åæ¢228 changeModuleThemeTab (value) {229 this.setConfig.moduleTheme.showList = value230 },231 // åæ¢è®¾ç½®å¼¹çªè®¾ç½®é¡¹ å
容ãæ ·å¼ãäºä»¶232 changeSetterContentTab (value) {233 this.setConfig.setterParam.setType = value234 this.refreshSetter()235 },236 changeSetterModuleElmentListTab (value) {237 this.setConfig.elementTheme.showList = value238 },239 // è·å模åæ¾ç¤ºå表240 getModuleThemeList () {241 let setConfig = this.setConfig242 let data = setConfig.moduleTheme.data243 for (let i in data) {244 if (data[i].tag == setConfig.moduleTheme.showList) {245 return data[i].data246 }247 }248 return []249 },250 getElementThemeList () {251 let setConfig = this.setConfig252 let data = setConfig.elementTheme.data253 for (let i in data) {254 if (data[i].tag == setConfig.elementTheme.showList) {255 return data[i].data256 }257 }258 return []259 },260 // åæ¢å³ä¾§å¯¼èªé¡µé¢ãå¼¹çªãå
¨å±è®¾ç½®261 changeSetContentType (value) {262 let setConfig = this.setConfig263 this.setContentType = value264 this.closeSetterPop()265 switch (value) {266 case 'pop':267 this.themeTabValue = 'element'268 break269 default:270 this.themeTabValue = 'module'271 break272 }273 setConfig.showElementPop = false274 setConfig.setModuleId = 'empty'275 setConfig.setElementId = 'empty'276 },277 // åæ¢æ¨¡åè®¾ç½®å¼¹çª è®¾ç½® å
ç´ 278 changePopContentType (value) {279 this.popContentType = value280 },281 // è·å设置项282 getSetterParam () {283 let setConfig = this.setConfig284 let data = setConfig.setterParam.data285 for (let i in data) {286 if (data[i].setType == setConfig.setterParam.setType) {287 return data[i].setList288 }289 }290 return []291 },292 // å·æ°è®¾ç½®å¼¹çª293 refreshSetter () {294 this.setConfig.setterKey = Math.random()295 },296 // å·æ°å
容297 refreshContent (type) {298 let { setConfig, contentConfig } = this299 this.refreshPageStyle()300 switch (this.setContentType) {301 case 'pop':302 this.popRandKey = Math.random()303 break304 default:305 Object.assign(setConfig.mainOrderSetterParam, {306 content: contentConfig.pages[setConfig.setPageId].content,307 editKey: setConfig.setModuleId,308 scrollTop: document.getElementById('mainSetter').scrollTop || 0,309 key: Math.random()310 })311 break312 }313 // history314 window.fc.historyArr = window.fc.historyArr || []315 window.fc.historyKey = window.fc.historyKey || 0316 if (JSON.stringify(contentConfig) != window.fc.historyArr[window.fc.historyKey]) {317 if (type != 'refreshHistory') {318 this.setHistory()319 this.checkHistoryBtnShow()320 }321 }322 },323 refreshPageStyle () {324 let contentConfig = this.contentConfig325 this.bodyStyle = this.formatStyle(contentConfig.body.style || {})326 this.pageStyle = this.formatStyle(contentConfig.pages[this.setConfig.setPageId].style || {})327 },328 // æ°å¢æ¨¡å329 addModule (item) {330 let { setConfig, contentConfig } = this331 item = JSON.parse(JSON.stringify(item))332 const addModule = item.config.module333 Object.assign(addModule, {334 id: this.getRandId()335 })336 let key = parseInt(setConfig.setModuleId)337 key = setConfig.setModuleId == 'empty' ? contentConfig.pages[setConfig.setPageId].content.length - 1 : key338 key = key < 0 ? 0 : key339 const newArr = []340 const content = JSON.parse(JSON.stringify(contentConfig.pages[setConfig.setPageId].content))341 for (let i = 0; i <= key; i++) {342 if (content[i]) {343 newArr.push(content[i])344 }345 }346 newArr.push(addModule)347 for (let j = key + 1; j < content.length; j++) {348 if (content[j]) {349 newArr.push(content[j])350 }351 }352 contentConfig.pages[setConfig.setPageId].content = newArr353 key++354 setConfig.setModuleId = key > newArr.length - 1 ? newArr.length - 1 : key355 this.refreshContent()356 setConfig.setType = 'module'357 this.setSetterContent()358 setConfig.showSetterPop = true359 if (item.config.elements) {360 this.addElement(item)361 }362 },363 contextShowElement (popContentType) {364 let setConfig = this.setConfig365 setConfig.setType = 'module'366 this.popContentType = popContentType367 this.setSetterContent()368 setConfig.showSetterPop = true369 this.contextmenuParam.show = false370 },371 contextMoveModule (type) {372 let { setConfig, contentConfig } = this373 let modules = JSON.parse(JSON.stringify(contentConfig.pages[setConfig.setPageId].content))374 setConfig.setModuleId = parseInt(setConfig.setModuleId)375 let blankItem376 switch (type) {377 case 'up':378 if (setConfig.setModuleId > 0) {379 blankItem = modules[setConfig.setModuleId - 1]380 modules[setConfig.setModuleId - 1] = modules[setConfig.setModuleId]381 modules[setConfig.setModuleId] = blankItem382 contentConfig.pages[setConfig.setPageId].content = modules383 setConfig.setModuleId = setConfig.setModuleId - 1384 }385 break386 case 'down':387 if (setConfig.setModuleId < modules.length - 1) {388 blankItem = modules[setConfig.setModuleId + 1]389 modules[setConfig.setModuleId + 1] = modules[setConfig.setModuleId]390 modules[setConfig.setModuleId] = blankItem391 contentConfig.pages[setConfig.setPageId].content = modules392 setConfig.setModuleId = setConfig.setModuleId + 1393 }394 break395 case 'top':396 if (setConfig.setModuleId > 0) {397 let popM = modules.splice(parseInt(setConfig.setModuleId), 1)398 contentConfig.pages[setConfig.setPageId].content = popM.concat(modules)399 setConfig.setModuleId = 0400 document.getElementById('mainSetter').scrollTop = 0401 }402 break403 case 'bottom':404 if (setConfig.setModuleId < modules.length - 1) {405 let popM = modules.splice(parseInt(setConfig.setModuleId), 1)406 contentConfig.pages[setConfig.setPageId].content = modules.concat(popM)407 setConfig.setModuleId = modules.length408 document.getElementById('mainSetter').scrollTop = document.getElementById('mainSetter').scrollHeight409 }410 break411 }412 this.refreshContent()413 setConfig.setType = 'module'414 this.setSetterContent()415 this.contextmenuParam.show = false416 },417 contextDelModule () {418 let setConfig = this.setConfig419 setConfig.mainOrderSetterParam.self.delContent(setConfig.setModuleId)420 this.contextmenuParam.show = false421 },422 contextCopyModule () {423 let setConfig = this.setConfig424 let addModule = this.contentConfig.pages[setConfig.setPageId].content[setConfig.setModuleId]425 addModule = JSON.parse(JSON.stringify(addModule))426 if (addModule.elements && addModule.elements.length) {427 for (let i in addModule.elements) {428 addModule.elements[i].id = this.getRandId()429 }430 }431 this.addModule({432 config: {433 module: addModule434 }435 })436 this.contextmenuParam.show = false437 },438 // æ°å¢å
ç´ 439 addElement (item, isPop) {440 let { setConfig, contentConfig } = this441 let setContent = isPop ? contentConfig.pops[setConfig.setPopId] : contentConfig.pages[setConfig.setPageId].content[setConfig.setModuleId]442 setContent.elements = setContent.elements || []443 let itemElements = JSON.parse(JSON.stringify(item)).config.elements444 let id445 for (let i in itemElements) {446 id = this.getRandId()447 setContent.elements.unshift(Object.assign(itemElements[i], {448 id449 }))450 }451 setConfig.setElementId = id452 setConfig.setType = 'element'453 this.refreshContent()454 this.setSetterContent()455 // console.log(setContent.elements)456 },457 contextLockElement (lock) {458 lock = lock || ''459 let setElementObj = this.getSetElementObj()460 setElementObj.elements[setElementObj.eid].lock = lock461 this.contextRefreshElement()462 },463 contextHideElement (hide) {464 hide = hide || ''465 let setElementObj = this.getSetElementObj()466 setElementObj.elements[setElementObj.eid].hide = hide467 this.contextRefreshElement()468 },469 contextCopyElement () {470 let setElementObj = this.getSetElementObj()471 setElementObj.elements.unshift(Object.assign(setElementObj.addElement, {472 id: this.getRandId()473 }))474 this.setConfig.setElementId = setElementObj.addElement.id475 this.contextRefreshElement()476 },477 contextDelElement () {478 let setConfig = this.setConfig479 let setElementObj = this.getSetElementObj()480 setElementObj.elements.splice(setElementObj.eid, 1)481 if (setElementObj.elements[0]) {482 document.getElementById('elementWindowSetter').scrollTop = 0483 this.setConfig.setElementId = setElementObj.elements[0].id484 this.contextRefreshElement()485 } else {486 setConfig.setType = 'page'487 if (this.setContentType == 'pop') {488 setConfig.setType = 'pop'489 }490 setConfig.setModuleId = 'empty'491 setConfig.setElementId = 'empty'492 this.setSetterContent()493 this.refreshContent()494 this.contextmenuParam.show = false495 }496 },497 contextMoveElement (type) {498 let { setConfig, contentConfig } = this499 let setElementObj = this.getSetElementObj()500 let blankItem501 switch (type) {502 case 'down':503 if (setElementObj.eid < setElementObj.elements.length - 1) {504 blankItem = setElementObj.elements[setElementObj.eid + 1]505 setElementObj.elements[setElementObj.eid + 1] = setElementObj.elements[setElementObj.eid]506 setElementObj.elements[setElementObj.eid] = blankItem507 }508 break509 case 'up':510 if (setElementObj.eid > 0) {511 blankItem = setElementObj.elements[setElementObj.eid - 1]512 setElementObj.elements[setElementObj.eid - 1] = setElementObj.elements[setElementObj.eid]513 setElementObj.elements[setElementObj.eid] = blankItem514 }515 break516 case 'bottom':517 if (setElementObj.eid < setElementObj.elements.length - 1) {518 let popM = setElementObj.elements.splice(parseInt(setElementObj.eid), 1)519 let elements = setElementObj.elements.concat(popM)520 if (this.setContentType == 'pop') {521 contentConfig.pops[setConfig.setPopId].elements = elements522 } else {523 contentConfig.pages[setConfig.setPageId].content[setConfig.setModuleId].elements = elements524 }525 }526 break527 case 'top':528 if (setElementObj.eid > 0) {529 let popM = setElementObj.elements.splice(parseInt(setElementObj.eid), 1)530 let elements = popM.concat(setElementObj.elements)531 if (this.setContentType == 'pop') {532 contentConfig.pops[setConfig.setPopId].elements = elements533 } else {534 contentConfig.pages[setConfig.setPageId].content[setConfig.setModuleId].elements = elements535 }536 }537 break538 }539 this.contextRefreshElement()540 },541 contextRefreshElement () {542 this.setConfig.setType = 'element'543 this.refreshContent()544 this.setSetterContent()545 this.contextmenuParam.show = false546 },547 getSetElementObj () {548 let { setConfig, contentConfig } = this549 let setContent = this.setContentType == 'pop' ? contentConfig.pops[setConfig.setPopId] : contentConfig.pages[setConfig.setPageId].content[setConfig.setModuleId]550 setContent.elements = setContent.elements || []551 let elements = setContent.elements552 let addElement553 let eid = 0554 for (let i in elements) {555 if (elements[i].id == setConfig.setElementId) {556 addElement = elements[i]557 eid = parseInt(i)558 }559 }560 if (addElement) {561 addElement = JSON.parse(JSON.stringify(addElement))562 }563 return {564 elements,565 addElement,566 eid567 }568 },569 // 主模åå表è¿åäºä»¶570 orderSetterEditContentCallback (key) {571 let setConfig = this.setConfig572 if (key !== undefined && key != 'move') {573 if (parseInt(key) != setConfig.setModuleId) {574 setConfig.setModuleId = key575 }576 setConfig.setType = 'module'577 this.setSetterContent()578 setConfig.showSetterPop = true579 }580 },581 orderSetterDelContentCallback (key) {582 let { setConfig, contentConfig } = this583 contentConfig.pages[setConfig.setPageId].content = setConfig.mainOrderSetterParam.content584 key = key - 1 > 0 ? key - 1 : 0585 setConfig.setModuleId = key586 this.refreshContent()587 setConfig.setType = 'module'588 if (contentConfig.pages[setConfig.setPageId].content.length <= 0) {589 setConfig.setType = 'page'590 }591 this.setSetterContent()592 },593 orderSetterMoveCallback (key) {594 let { setConfig, contentConfig } = this595 contentConfig.pages[setConfig.setPageId].content = setConfig.mainOrderSetterParam.content596 setConfig.setModuleId = key597 this.refreshContent()598 setConfig.setType = 'module'599 this.setSetterContent()600 },601 // 设置é
ç½®å
容602 setSetterContent (refreshHistory) {603 let { setConfig, contentConfig } = this604 setConfig.showElementPop = false605 switch (setConfig.setType) {606 case 'module':607 let setModule = contentConfig.pages[setConfig.setPageId].content[setConfig.setModuleId]608 let setModuleParams = setConfig.moduleThemeSet[setModule.tag]609 for (let i in setModuleParams) {610 if (setModuleParams[i].theme == setModule.theme) {611 setConfig.setterParam = setModuleParams[i]612 }613 }614 setConfig.setterParam.setType = 'content'615 setConfig.moduleContentSetterKey = 'empty'616 setConfig.setElementId = 'empty'617 setConfig.setterParamValue = setModule618 if (setModule.elements && setModule.elements.length) {619 Object.assign(setConfig.elementWindowSetterParam, {620 content: setModule.elements,621 scrollTop: document.getElementById('elementWindowSetter').scrollTop || 0,622 key: Math.random()623 })624 setConfig.showElementPop = true625 }626 break627 case 'page':628 this.popContentType = 'set'629 setConfig.setterParam = setConfig.pageSetParam630 setConfig.setterParamValue = contentConfig.pages[setConfig.setPageId]631 setConfig.setterParamValue.style = setConfig.setterParamValue.style || {}632 break633 case 'pop':634 this.popContentType = 'set'635 setConfig.setterParam = setConfig.popSetParam636 setConfig.setterParamValue = contentConfig.pops[setConfig.setPopId]637 setConfig.setterParamValue.style = setConfig.setterParamValue.style || {}638 break639 case 'element':640 this.popContentType = 'set'641 let elements642 if (this.setContentType == 'pop') {643 elements = contentConfig.pops[setConfig.setPopId].elements644 } else {645 elements = contentConfig.pages[setConfig.setPageId].content[setConfig.setModuleId].elements646 }647 let setElement = {}648 let editKey = 0649 for (let i in elements) {650 if (elements[i].id == setConfig.setElementId) {651 setElement = elements[i]652 editKey = i653 }654 }655 let setElementParams = setConfig.elementThemeSet[setElement.tag]656 for (let i in setElementParams) {657 if (setElementParams[i].theme == setElement.theme) {658 setConfig.setterParam = setElementParams[i]659 }660 }661 setConfig.setterParam.setType = 'style'662 setConfig.setterParamValue = setElement663 // elementwindow664 Object.assign(setConfig.elementWindowSetterParam, {665 content: elements,666 editKey,667 scrollTop: document.getElementById('elementWindowSetter').scrollTop || 0,668 key: Math.random()669 })670 setConfig.showElementPop = true671 break672 }673 this.refreshSetter()674 if (refreshHistory) {675 this.setHistory()676 this.checkHistoryBtnShow()677 }678 },679 // å
ç´ å¼¹çªè¿åäºä»¶680 elementWindowSetterEditContentCallback (key) {681 let setConfig = this.setConfig682 if (key !== undefined && key != 'move') {683 setConfig.elementWindowSetterParam.editKey = key684 setConfig.setElementId = setConfig.elementWindowSetterParam.content[key].id685 setConfig.setType = 'element'686 this.setSetterContent()687 setConfig.showSetterPop = true688 }689 },690 elementWindowSetterDelContentCallback (key) {691 let { setConfig, contentConfig } = this692 if (this.setContentType == 'pop') {693 contentConfig.pops[setConfig.setPopId].elements = setConfig.elementWindowSetterParam.content694 } else {695 contentConfig.pages[setConfig.setPageId].content[setConfig.setModuleId].elements = setConfig.elementWindowSetterParam.content696 }697 key = key - 1 > 0 ? key - 1 : 0698 setConfig.setElementId = setConfig.elementWindowSetterParam.content[key].id699 this.refreshContent()700 setConfig.setType = 'element'701 if (setConfig.elementWindowSetterParam.content.length <= 0) {702 setConfig.setType = 'page'703 }704 this.setSetterContent()705 },706 elementWindowSetterMoveCallback (key) {707 let { setConfig, contentConfig } = this708 if (this.setContentType == 'pop') {709 contentConfig.pops[setConfig.setPopId].elements = setConfig.elementWindowSetterParam.content710 } else {711 contentConfig.pages[setConfig.setPageId].content[setConfig.setModuleId].elements = setConfig.elementWindowSetterParam.content712 }713 setConfig.setElementId = setConfig.elementWindowSetterParam.content[key].id714 this.refreshContent()715 setConfig.setType = 'element'716 this.setSetterContent()717 },718 // æ°å¢é¡µé¢719 addPage () {720 let { setConfig, contentConfig } = this721 let pageId = this.getRandId()722 contentConfig.pages.push({723 name: '页é¢' + (contentConfig.pages.length + 1),724 content: [],725 id: pageId726 })727 setConfig.setPageId = contentConfig.pages.length - 1728 this.refreshPageList(true)729 this.refreshContent()730 setConfig.setType = 'page'731 this.setSetterContent()732 },733 // å¤å¶é¡µé¢734 copyPage (item, key) {735 let { setConfig, contentConfig } = this736 let pageId = this.getRandId()737 let copyItem = JSON.parse(JSON.stringify(item))738 const newArr = []739 const content = JSON.parse(JSON.stringify(contentConfig.pages))740 for (let i = 0; i <= key; i++) {741 if (content[i]) {742 newArr.push(content[i])743 }744 }745 newArr.push(Object.assign(copyItem, {746 id: pageId747 }))748 for (let j = key + 1; j < content.length; j++) {749 if (content[j]) {750 newArr.push(content[j])751 }752 }753 contentConfig.pages = newArr754 setConfig.setPageId = key + 1755 this.refreshPageList()756 this.refreshContent()757 setConfig.setType = 'page'758 this.setSetterContent()759 },760 // å é¤é¡µé¢761 delPage (key) {762 let { setConfig } = this763 setConfig.pageListOrderSetterParam.self.delOrderIcon(key)764 setConfig.setType = 'page'765 this.setSetterContent()766 },767 // æ¾ç¤ºé¡µé¢å表èå768 showPageMenu (item) {769 let { setConfig } = this770 let content = setConfig.pageListOrderSetterParam.content771 for (let i in content) {772 content[i].showMenu = false773 }774 item.showMenu = true775 setConfig.pageMenuShowing = true776 },777 // å·æ°é¡µé¢å表778 refreshPageList (isAdd) {779 let { setConfig, contentConfig } = this780 Object.assign(setConfig.pageListOrderSetterParam, {781 content: contentConfig.pages,782 editKey: setConfig.setPageId,783 scrollTop: isAdd ? document.getElementById('pageListOrderSetter').scrollHeight : document.getElementById('pageListOrderSetter').scrollTop,784 key: Math.random()785 })786 },787 // 页é¢å表è¿åäºä»¶788 pageListOrderSetterEditContentCallback (key) {789 let { setConfig } = this790 if (key !== undefined && key != 'move') {791 setConfig.setPageId = key792 this.refreshContent()793 setConfig.setType = 'page'794 this.setSetterContent()795 setConfig.showSetterPop = true796 }797 },798 pageListOrderSetterDelContentCallback (key) {799 let { setConfig, contentConfig } = this800 contentConfig.pages = setConfig.pageListOrderSetterParam.content801 setConfig.setPageId = key - 1 > 0 ? key - 1 : 0802 this.refreshPageList()803 this.refreshContent()804 setConfig.setType = 'page'805 this.setSetterContent()806 },807 pageListOrderSetterMoveCallback (key) {808 let { setConfig, contentConfig } = this809 contentConfig.pages = setConfig.pageListOrderSetterParam.content810 setConfig.setPageId = key811 this.refreshPageList()812 this.refreshContent()813 setConfig.setType = 'page'814 this.setSetterContent()815 },816 // æ°å¢å¼¹çª817 addPop () {818 let { setConfig, contentConfig } = this819 let popId = this.getRandId()820 contentConfig.pops.push({821 name: 'å¼¹çª' + (contentConfig.pops.length + 1),822 content: [],823 id: popId824 })825 setConfig.setPopId = contentConfig.pops.length - 1826 this.refreshPopList(true)827 this.refreshContent()828 setConfig.setType = 'pop'829 this.setSetterContent()830 },831 // å¤å¶å¼¹çª832 copyPop (item, key) {833 let { setConfig, contentConfig } = this834 let popId = this.getRandId()835 let copyItem = JSON.parse(JSON.stringify(item))836 const newArr = []837 const content = JSON.parse(JSON.stringify(contentConfig.pops))838 for (let i = 0; i <= key; i++) {839 if (content[i]) {840 newArr.push(content[i])841 }842 }843 newArr.push(Object.assign(copyItem, {844 id: popId845 }))846 for (let j = key + 1; j < content.length; j++) {847 if (content[j]) {848 newArr.push(content[j])849 }850 }851 contentConfig.pops = newArr852 setConfig.setPopId = key + 1853 this.refreshPopList()854 this.refreshContent()855 setConfig.setType = 'pop'856 this.setSetterContent()857 },858 // 设置弹çªæ¨¡ç859 setPopTheme (item) {860 window.fc.Dialog.show({861 text: '使ç¨å¼¹çªæ¨¡çå°è¦çå½åå¼¹çªå
容ï¼ç¡®å®ä½¿ç¨åï¼',862 clearText: 'åæ¶',863 confirmCallback: () => {864 let { setConfig, contentConfig } = this865 let pop = contentConfig.pops[setConfig.setPopId]866 // console.log(JSON.stringify(pop))867 let id = pop.id868 let data = JSON.parse(item.data)869 data.id = id870 contentConfig.pops[setConfig.setPopId] = data871 this.refreshContent()872 }873 })874 },875 // 设置页é¢æ¨¡ç876 setPageTheme (item) {877 window.fc.Dialog.show({878 text: '使ç¨é¡µé¢æ¨¡çå°ä¼è¦çå½å页é¢è®¾ç½®ï¼ç¡®å®ä½¿ç¨åï¼',879 clearText: 'åæ¶',880 confirmCallback: () => {881 let data = JSON.parse(item.data)882 this.$store.state.contentConfig.pages[this.setConfig.setPageId] = data.pages[0]883 this.refreshPageList()884 this.refreshContent()885 }886 })887 },888 // å é¤å¼¹çª889 delPop (key) {890 this.setConfig.popListOrderSetterParam.self.delOrderIcon(key)891 },892 // æ¾ç¤ºå¼¹çªå表èå893 showPopMenu (item) {894 let { setConfig } = this895 let content = setConfig.popListOrderSetterParam.content896 for (let i in content) {897 content[i].showMenu = false898 }899 item.showMenu = true900 setConfig.popMenuShowing = true901 },902 // å·æ°å¼¹çªå表903 refreshPopList (isAdd) {904 let { setConfig, contentConfig } = this905 setConfig.popListOrderSetterParam.content = contentConfig.pops906 if (document.getElementById('popListOrderSetter')) {907 if (isAdd) {908 setConfig.popListOrderSetterParam.scrollTop = document.getElementById('popListOrderSetter').scrollHeight909 document.getElementById('popListOrderSetter').scrollTop = document.getElementById('popListOrderSetter').scrollHeight910 } else {911 setConfig.popListOrderSetterParam.scrollTop = document.getElementById('popListOrderSetter').scrollTop912 }913 }914 setConfig.popListOrderSetterParam.key = Math.random()915 setTimeout(() => {916 setConfig.popListOrderSetterParam.self.refresh(setConfig.setPopId)917 })918 },919 // å¼¹çªå表è¿åäºä»¶920 popListOrderSetterEditContentCallback (key) {921 let { setConfig } = this922 if (key !== undefined && key != 'move') {923 setConfig.setPopId = key || 0924 this.refreshContent()925 setConfig.setType = 'pop'926 this.setSetterContent()927 setConfig.showSetterPop = true928 }929 },930 popListOrderSetterDelContentCallback (key) {931 let { setConfig, contentConfig } = this932 contentConfig.pops = setConfig.popListOrderSetterParam.content933 setConfig.setPopId = key - 1 > 0 ? key - 1 : 0934 this.refreshPopList()935 this.refreshContent()936 setConfig.setType = 'pop'937 this.setSetterContent()938 },939 popListOrderSetterMoveCallback (key) {940 let { setConfig, contentConfig } = this941 contentConfig.pops = setConfig.popListOrderSetterParam.content942 setConfig.setPopId = key || 0943 this.refreshPopList()944 this.refreshContent()945 setConfig.setType = 'pop'946 this.setSetterContent()947 },948 emptyClick (e) {949 let { setConfig } = this950 if (e.target == e.currentTarget) {951 setConfig.setType = 'page'952 if (this.setContentType == 'pop') {953 setConfig.setType = 'pop'954 }955 setConfig.setModuleId = 'empty'956 setConfig.setElementId = 'empty'957 setConfig.showSetterPop = true958 this.setSetterContent()959 const doms = setConfig.mainOrderSetterParam.self.scroll.getElementsByClassName('selectedBorder')960 if (doms && doms.length) {961 for (let i = 0; i < doms.length; i++) {962 doms[i].style.border = 'none'963 }964 }965 }966 },967 keySetElementSize (type, size) {968 let { setConfig } = this969 let setElement = setConfig.setterParamValue970 if (setConfig.setType != 'element' || !setElement) {971 return false972 }973 setElement.elementStyle.width = parseInt(setElement.elementStyle.width) || 0974 setElement.elementStyle.height = parseInt(setElement.elementStyle.height) || 0975 switch (setConfig.setType) {976 case 'element':977 case 'popElement':978 switch (type) {979 case 'left':980 setElement.elementStyle.width -= size981 break982 case 'right':983 setElement.elementStyle.width += size984 break985 case 'up':986 setElement.elementStyle.height -= size987 break988 case 'down':989 setElement.elementStyle.height += size990 break991 }992 break993 }994 this.refreshContent()995 this.refreshSetter()996 },997 keySetElementPos (type, size) {998 let { setConfig } = this999 let setElement = setConfig.setterParamValue1000 if (setConfig.setType != 'element' || !setElement) {1001 return false1002 }1003 setElement.elementStyle.left = parseInt(setElement.elementStyle.left) || 01004 setElement.elementStyle.top = parseInt(setElement.elementStyle.top) || 01005 switch (setConfig.setType) {1006 case 'element':1007 case 'popElement':1008 switch (type) {1009 case 'left':1010 setElement.elementStyle.left -= size1011 break1012 case 'right':1013 setElement.elementStyle.left += size1014 break1015 case 'up':1016 setElement.elementStyle.top -= size1017 break1018 case 'down':1019 setElement.elementStyle.top += size1020 break1021 }1022 break1023 }1024 this.refreshContent()1025 this.refreshSetter()1026 },1027 keyActionInit () {1028 // é®çäºä»¶1029 let keyType = 'pos'1030 let keyAddSize = 11031 let keyObj = {1032 37: 'left',1033 38: 'up',1034 39: 'right',1035 40: 'down'1036 }1037 document.onkeydown = (e) => {1038 switch (e.keyCode) {1039 case 16:1040 keyAddSize = 101041 break1042 case 17:1043 keyType = 'size'1044 break1045 }1046 }1047 document.onkeyup = (e) => {1048 switch (e.keyCode) {1049 case 16:1050 keyAddSize = 11051 break1052 case 17:1053 keyType = 'pos'1054 break1055 case 37:1056 case 38:1057 case 39:1058 case 40:1059 if (keyType == 'size') {1060 this.keySetElementSize(keyObj[e.keyCode], keyAddSize)1061 } else {1062 this.keySetElementPos(keyObj[e.keyCode], keyAddSize)1063 }1064 break1065 case 89:1066 if (keyType == 'size') {1067 this.historyAhead()1068 }1069 break1070 case 90:1071 if (keyType == 'size') {1072 this.historyUndo()1073 }1074 break1075 }1076 }1077 },1078 checkHistoryBtnShow () {1079 if (window.fc.historyArr.length && window.fc.historyKey) {1080 this.showUndo = true1081 } else {1082 this.showUndo = false1083 }1084 if (window.fc.historyArr.length && window.fc.historyKey < window.fc.historyArr.length - 1) {1085 this.showAhead = true1086 } else {1087 this.showAhead = false1088 }1089 },1090 setHistory () {1091 const contentConfigCatch = JSON.stringify(this.contentConfig)1092 window.fc.historyArr.push(contentConfigCatch)1093 sessionStorage.setItem('configContentCatch', contentConfigCatch)1094 if (window.fc.historyArr.length > 10) {1095 window.fc.historyArr.shift()1096 }1097 window.fc.historyKey = window.fc.historyArr.length - 11098 },1099 historyUndo () {1100 if (!this.showUndo) {1101 return false1102 }1103 window.fc.historyKey--1104 window.fc.historyKey = window.fc.historyKey > 0 ? window.fc.historyKey : 01105 if (window.fc.historyArr[window.fc.historyKey]) {1106 this.$store.state.contentConfig = JSON.parse(window.fc.historyArr[window.fc.historyKey])1107 this.refreshContent('refreshHistory')1108 this.refreshPageList()1109 this.refreshSetter()1110 this.checkHistoryBtnShow()1111 }1112 },1113 historyAhead () {1114 if (!this.showAhead) {1115 return false1116 }1117 window.fc.historyKey++1118 window.fc.historyKey = window.fc.historyKey < window.fc.historyArr.length ? window.fc.historyKey : window.fc.historyArr.length - 11119 if (window.fc.historyArr[window.fc.historyKey]) {1120 this.$store.state.contentConfig = JSON.parse(window.fc.historyArr[window.fc.historyKey])1121 this.refreshContent('refreshHistory')1122 this.refreshPageList()1123 this.refreshSetter()1124 this.checkHistoryBtnShow()1125 }1126 }1127 }, PublicFunc, FormatFunc)1128}...
config.test.js
Source:config.test.js
...20 const isClientSide = require('src/isClientSide').default21 isClientSide.mockReturnValue(false)22 const { getConfig, setConfig } = require('src/config')23 const mockConfig = createMockConfig()24 setConfig(mockConfig)25 expect(getConfig()).toEqual(mockConfig)26 })27 it('[client-side] returns the set config with defaults', () => {28 expect.assertions(1)29 const isClientSide = require('src/isClientSide').default30 isClientSide.mockReturnValue(true)31 const { getConfig, setConfig } = require('src/config')32 const mockConfig = {33 ...createMockConfig(),34 cookies: undefined,35 }36 const expectedConfig = {37 ...mockConfig,38 // Default cookies values.39 cookies: {40 name: undefined,41 keys: undefined,42 domain: undefined,43 httpOnly: true,44 maxAge: 604800000, // week45 overwrite: true,46 path: '/',47 sameSite: 'strict',48 secure: true,49 signed: true,50 },51 }52 setConfig(mockConfig)53 expect(getConfig()).toEqual(expectedConfig)54 })55 it('[client-side] throws if the user does not define the firebaseClientInitConfig', () => {56 expect.assertions(1)57 const isClientSide = require('src/isClientSide').default58 isClientSide.mockReturnValue(true)59 const { setConfig } = require('src/config')60 const mockConfig = {61 ...createMockConfig(),62 firebaseClientInitConfig: undefined,63 }64 expect(() => {65 setConfig(mockConfig)66 }).toThrow(67 'Invalid next-firebase-auth options: The "firebaseClientInitConfig.apiKey" value is required.'68 )69 })70 it('[client-side] throws if the user provides firebaseClientInitConfig without an API key', () => {71 expect.assertions(1)72 const isClientSide = require('src/isClientSide').default73 isClientSide.mockReturnValue(true)74 const { setConfig } = require('src/config')75 const mockConfig = {76 ...createMockConfig(),77 firebaseClientInitConfig: {78 apiKey: undefined,79 },80 }81 expect(() => {82 setConfig(mockConfig)83 }).toThrow(84 'Invalid next-firebase-auth options: The "firebaseClientInitConfig.apiKey" value is required.'85 )86 })87 it('[server-side] throws if the user does not define the firebaseClientInitConfig', () => {88 expect.assertions(1)89 const isClientSide = require('src/isClientSide').default90 isClientSide.mockReturnValue(false)91 const { setConfig } = require('src/config')92 const mockConfig = {93 ...createMockConfig(),94 firebaseClientInitConfig: undefined,95 }96 expect(() => {97 setConfig(mockConfig)98 }).toThrow(99 'Invalid next-firebase-auth options: The "firebaseClientInitConfig.apiKey" value is required.'100 )101 })102 it('[server-side] throws if the user provides firebaseClientInitConfig without an API key', () => {103 expect.assertions(1)104 const isClientSide = require('src/isClientSide').default105 isClientSide.mockReturnValue(false)106 const { setConfig } = require('src/config')107 const mockConfig = {108 ...createMockConfig(),109 firebaseClientInitConfig: {110 firebaseClientInitConfig: {111 apiKey: undefined,112 },113 },114 }115 expect(() => {116 setConfig(mockConfig)117 }).toThrow(118 'Invalid next-firebase-auth options: The "firebaseClientInitConfig.apiKey" value is required.'119 )120 })121 it('[client-side] does not throw if the user provides firebaseAdminInitConfig on the client side, as long as the private key is not set', () => {122 expect.assertions(1)123 const isClientSide = require('src/isClientSide').default124 isClientSide.mockReturnValue(true)125 const { setConfig } = require('src/config')126 const mockConfig = {127 ...createMockConfig(),128 firebaseAdminInitConfig: {129 credential: {130 projectId: 'abc',131 clientEmail: 'def',132 privateKey: undefined,133 },134 databaseURL: 'ghi',135 },136 }137 expect(() => {138 setConfig(mockConfig)139 }).not.toThrow()140 })141 it('[client-side] throws if the user provides firebaseAdminInitConfig.credential.privateKey on the client side', () => {142 expect.assertions(1)143 const isClientSide = require('src/isClientSide').default144 isClientSide.mockReturnValue(true)145 const { setConfig } = require('src/config')146 const mockConfig = {147 ...createMockConfig(),148 firebaseAdminInitConfig: {149 credential: {150 projectId: 'abc',151 clientEmail: 'def',152 privateKey: 'oops',153 },154 databaseURL: 'ghi',155 },156 }157 expect(() => {158 setConfig(mockConfig)159 }).toThrow(160 'Invalid next-firebase-auth options: The "firebaseAdminInitConfig" private key setting should not be available on the client side.'161 )162 })163 it('[client-side] throws if the user provides a cookies.keys value', () => {164 expect.assertions(1)165 const isClientSide = require('src/isClientSide').default166 isClientSide.mockReturnValue(true)167 const { setConfig } = require('src/config')168 const mockConfigDefault = createMockConfig()169 const mockConfig = {170 ...mockConfigDefault,171 cookies: {172 ...mockConfigDefault.cookies,173 keys: 'thing',174 },175 }176 expect(() => {177 setConfig(mockConfig)178 }).toThrow(179 'Invalid next-firebase-auth options: The "cookies.keys" setting should not be available on the client side.'180 )181 })182 it('[client-side] throws if the user provides a cookies.keys array', () => {183 expect.assertions(1)184 const isClientSide = require('src/isClientSide').default185 isClientSide.mockReturnValue(true)186 const { setConfig } = require('src/config')187 const mockConfigDefault = createMockConfig()188 const mockConfig = {189 ...mockConfigDefault,190 cookies: {191 ...mockConfigDefault.cookies,192 keys: ['some', 'keys'],193 },194 }195 expect(() => {196 setConfig(mockConfig)197 }).toThrow(198 'Invalid next-firebase-auth options: The "cookies.keys" setting should not be available on the client side.'199 )200 })201 it('[client-side] does not throw if the user provides an undefined cookies.keys value', () => {202 expect.assertions(1)203 const isClientSide = require('src/isClientSide').default204 isClientSide.mockReturnValue(true)205 const { setConfig } = require('src/config')206 const mockConfigDefault = createMockConfig()207 const mockConfig = {208 ...mockConfigDefault,209 cookies: {210 ...mockConfigDefault.cookies,211 keys: undefined,212 },213 }214 expect(() => {215 setConfig(mockConfig)216 }).not.toThrow()217 })218 it('[client-side] does not throw if the user provides an empty cookies.keys array', () => {219 expect.assertions(1)220 const isClientSide = require('src/isClientSide').default221 isClientSide.mockReturnValue(true)222 const { setConfig } = require('src/config')223 const mockConfigDefault = createMockConfig()224 const mockConfig = {225 ...mockConfigDefault,226 cookies: {227 ...mockConfigDefault.cookies,228 keys: [],229 },230 }231 expect(() => {232 setConfig(mockConfig)233 }).not.toThrow()234 })235 it('[client-side] does not throw if the user provides a cookies.keys array with only undefined values', () => {236 expect.assertions(1)237 const isClientSide = require('src/isClientSide').default238 isClientSide.mockReturnValue(true)239 const { setConfig } = require('src/config')240 const mockConfigDefault = createMockConfig()241 const mockConfig = {242 ...mockConfigDefault,243 cookies: {244 ...mockConfigDefault.cookies,245 keys: [undefined, undefined],246 },247 }248 expect(() => {249 setConfig(mockConfig)250 }).not.toThrow()251 })252 it('[server-side] throws if the user does not provide cookies.name', () => {253 expect.assertions(1)254 const isClientSide = require('src/isClientSide').default255 isClientSide.mockReturnValue(false)256 const { setConfig } = require('src/config')257 const mockConfigDefault = createMockConfig()258 const mockConfig = {259 ...mockConfigDefault,260 cookies: {261 ...mockConfigDefault.cookies,262 name: undefined,263 },264 }265 expect(() => {266 setConfig(mockConfig)267 }).toThrow(268 'Invalid next-firebase-auth options: The "cookies.name" setting is required on the server side.'269 )270 })271 it('[server-side] throws if the user does not provide cookies.keys but is using signed cookies', () => {272 expect.assertions(1)273 const isClientSide = require('src/isClientSide').default274 isClientSide.mockReturnValue(false)275 const { setConfig } = require('src/config')276 const mockConfigDefault = createMockConfig()277 const mockConfig = {278 ...mockConfigDefault,279 cookies: {280 ...mockConfigDefault.cookies,281 keys: undefined,282 signed: true,283 },284 }285 expect(() => {286 setConfig(mockConfig)287 }).toThrow(288 'Invalid next-firebase-auth options: The "cookies.keys" setting must be set if "cookies.signed" is true.'289 )290 })291 it('[server-side] throws if the user provides an empty cookies.keys array but is using signed cookies', () => {292 expect.assertions(1)293 const isClientSide = require('src/isClientSide').default294 isClientSide.mockReturnValue(false)295 const { setConfig } = require('src/config')296 const mockConfigDefault = createMockConfig()297 const mockConfig = {298 ...mockConfigDefault,299 cookies: {300 ...mockConfigDefault.cookies,301 keys: [],302 signed: true,303 },304 }305 expect(() => {306 setConfig(mockConfig)307 }).toThrow(308 'Invalid next-firebase-auth options: The "cookies.keys" setting must be set if "cookies.signed" is true.'309 )310 })311 it('[server-side] throws if the user provides an cookies.keys array with only undefined values but is using signed cookies', () => {312 expect.assertions(1)313 const isClientSide = require('src/isClientSide').default314 isClientSide.mockReturnValue(false)315 const { setConfig } = require('src/config')316 const mockConfigDefault = createMockConfig()317 const mockConfig = {318 ...mockConfigDefault,319 cookies: {320 ...mockConfigDefault.cookies,321 keys: [undefined, undefined],322 signed: true,323 },324 }325 expect(() => {326 setConfig(mockConfig)327 }).toThrow(328 'Invalid next-firebase-auth options: The "cookies.keys" setting must be set if "cookies.signed" is true.'329 )330 })331 it('[server-side] throws if the user sets a maxAge of greater than two weeks', () => {332 expect.assertions(1)333 const isClientSide = require('src/isClientSide').default334 isClientSide.mockReturnValue(false)335 const { setConfig } = require('src/config')336 const mockConfigDefault = createMockConfig()337 const mockConfig = {338 ...mockConfigDefault,339 cookies: {340 ...mockConfigDefault.cookies,341 maxAge: 14 * 86400000 + 2, // two ms greater than 14 days342 },343 }344 expect(() => {345 setConfig(mockConfig)346 }).toThrow(347 'Invalid next-firebase-auth options: The "cookies.maxAge" setting must be less than two weeks (1209600000 ms).'348 )349 })350 it('throws if the tokenChangedHandler and loginAPIEndpoint are not defined', () => {351 expect.assertions(1)352 const { setConfig } = require('src/config')353 const mockConfigDefault = createMockConfig()354 const mockConfig = {355 ...mockConfigDefault,356 loginAPIEndpoint: undefined,357 }358 expect(() => {359 setConfig(mockConfig)360 }).toThrow(361 'Invalid next-firebase-auth options: The "loginAPIEndpoint" setting is required.'362 )363 })364 it('throws if the tokenChangedHandler and logoutAPIEndpoint are not defined', () => {365 expect.assertions(1)366 const { setConfig } = require('src/config')367 const mockConfigDefault = createMockConfig()368 const mockConfig = {369 ...mockConfigDefault,370 logoutAPIEndpoint: undefined,371 }372 expect(() => {373 setConfig(mockConfig)374 }).toThrow(375 'Invalid next-firebase-auth options: The "logoutAPIEndpoint" setting is required.'376 )377 })378 it('throws if both the tokenChangedHandler and loginAPIEndpoint are defined', () => {379 expect.assertions(1)380 const { setConfig } = require('src/config')381 const mockConfigDefault = createMockConfig()382 const mockConfig = {383 ...mockConfigDefault,384 tokenChangedHandler: async (token) => token,385 }386 expect(() => {387 setConfig(mockConfig)388 }).toThrow(389 'The "loginAPIEndpoint" setting should not be set if you are using a "tokenChangedHandler".'390 )391 })392 it('throws if both the tokenChangedHandler and logoutAPIEndpoint are defined', () => {393 expect.assertions(1)394 const { setConfig } = require('src/config')395 const mockConfigDefault = createMockConfig()396 const mockConfig = {397 ...mockConfigDefault,398 tokenChangedHandler: async (token) => token,399 }400 expect(() => {401 setConfig(mockConfig)402 }).toThrow(403 'The "logoutAPIEndpoint" setting should not be set if you are using a "tokenChangedHandler".'404 )405 })406 it('throws if both the tokenChangedHandler and onLoginRequestError are defined', () => {407 expect.assertions(1)408 const { setConfig } = require('src/config')409 const mockConfigDefault = createMockConfig()410 const mockConfig = {411 ...mockConfigDefault,412 loginAPIEndpoint: undefined,413 logoutAPIEndpoint: undefined,414 onLoginRequestError: () => {},415 tokenChangedHandler: async (token) => token,416 }417 expect(() => {418 setConfig(mockConfig)419 }).toThrow(420 'The "onLoginRequestError" setting should not be set if you are using a "tokenChangedHandler".'421 )422 })423 it('throws if both the tokenChangedHandler and onLogoutRequestError are defined', () => {424 expect.assertions(1)425 const { setConfig } = require('src/config')426 const mockConfigDefault = createMockConfig()427 const mockConfig = {428 ...mockConfigDefault,429 loginAPIEndpoint: undefined,430 logoutAPIEndpoint: undefined,431 onLogoutRequestError: () => {},432 tokenChangedHandler: async (token) => token,433 }434 expect(() => {435 setConfig(mockConfig)436 }).toThrow(437 'The "onLogoutRequestError" setting should not be set if you are using a "tokenChangedHandler".'438 )439 })440 it('throws if onLoginRequestError is not a function', () => {441 expect.assertions(1)442 const { setConfig } = require('src/config')443 const mockConfigDefault = createMockConfig()444 const mockConfig = {445 ...mockConfigDefault,446 onLoginRequestError: 'no errors please',447 }448 expect(() => {449 setConfig(mockConfig)450 }).toThrow(451 'Invalid next-firebase-auth options: The "onLoginRequestError" setting must be a function.'452 )453 })454 it('throws if onLogoutRequestError is not a function', () => {455 expect.assertions(1)456 const { setConfig } = require('src/config')457 const mockConfigDefault = createMockConfig()458 const mockConfig = {459 ...mockConfigDefault,460 onLogoutRequestError: 'no errors please',461 }462 expect(() => {463 setConfig(mockConfig)464 }).toThrow(465 'Invalid next-firebase-auth options: The "onLogoutRequestError" setting must be a function.'466 )467 })468 it('throws if the config.firebaseAuthEmulator has a http or https prefix', () => {469 expect.assertions(1)470 const { setConfig } = require('src/config')471 const mockConfigDefault = createMockConfig()472 const mockConfig = {473 ...mockConfigDefault,474 firebaseAuthEmulatorHost: 'http://localhost:9099',475 }476 expect(() => {477 setConfig(mockConfig)478 }).toThrow(479 'Invalid next-firebase-auth options: The firebaseAuthEmulatorHost should be set without a prefix (e.g., localhost:9099)'480 )481 })482 it('[server-side] throws if config.firebaseAuthEmulatorHost is set, but not the FIREBASE_AUTH_EMULATOR_HOST env var', () => {483 expect.assertions(1)484 const isClientSide = require('src/isClientSide').default485 isClientSide.mockReturnValue(false)486 const { setConfig } = require('src/config')487 const mockConfigDefault = createMockConfig()488 const mockConfig = {489 ...mockConfigDefault,490 firebaseAuthEmulatorHost: 'localhost:9099',491 }492 expect(() => {493 setConfig(mockConfig)494 }).toThrow(495 'The "FIREBASE_AUTH_EMULATOR_HOST" environment variable should be set if you are using the "firebaseAuthEmulatorHost" option'496 )497 })498 it('[server-side] throws if the FIREBASE_AUTH_EMULATOR_HOST env var differs from the one set in the config', () => {499 expect.assertions(1)500 const isClientSide = require('src/isClientSide').default501 isClientSide.mockReturnValue(false)502 const { setConfig } = require('src/config')503 const mockConfigDefault = createMockConfig()504 const mockConfig = {505 ...mockConfigDefault,506 firebaseAuthEmulatorHost: 'localhost:9099',507 }508 process.env.FIREBASE_AUTH_EMULATOR_HOST = 'localhost:8088'509 expect(() => {510 setConfig(mockConfig)511 }).toThrow(512 'The "FIREBASE_AUTH_EMULATOR_HOST" environment variable should be the same as the host set in the config'513 )514 })515 it('[server-side] should not throw if the FIREBASE_AUTH_EMULATOR_HOST env variable is set and matches the one set in the config', () => {516 expect.assertions(1)517 const isClientSide = require('src/isClientSide').default518 isClientSide.mockReturnValue(false)519 const { setConfig } = require('src/config')520 const mockConfigDefault = createMockConfig()521 const mockConfig = {522 ...mockConfigDefault,523 firebaseAuthEmulatorHost: 'localhost:9099',524 }525 process.env.FIREBASE_AUTH_EMULATOR_HOST = 'localhost:9099'526 expect(() => {527 setConfig(mockConfig)528 }).not.toThrow()529 })530 it('does not throw if onVerifyTokenError is undefined', () => {531 expect.assertions(1)532 const { setConfig } = require('src/config')533 const mockConfigDefault = createMockConfig()534 const mockConfig = {535 ...mockConfigDefault,536 onVerifyTokenError: undefined,537 }538 expect(() => {539 setConfig(mockConfig)540 }).not.toThrow()541 })542 it('defaults onVerifyTokenError to a function', () => {543 expect.assertions(1)544 const { getConfig, setConfig } = require('src/config')545 const mockConfigDefault = createMockConfig()546 delete mockConfigDefault.onVerifyTokenError547 setConfig(mockConfigDefault)548 const config = getConfig()549 expect(typeof config.onVerifyTokenError).toEqual('function')550 })551 it('throws if onVerifyTokenError is not a function', () => {552 expect.assertions(1)553 const { setConfig } = require('src/config')554 const mockConfigDefault = createMockConfig()555 const mockConfig = {556 ...mockConfigDefault,557 onVerifyTokenError: 'no errors please',558 }559 expect(() => {560 setConfig(mockConfig)561 }).toThrow(562 'Invalid next-firebase-auth options: The "onVerifyTokenError" setting must be a function.'563 )564 })565 it('does not throw if onTokenRefreshError is undefined', () => {566 expect.assertions(1)567 const { setConfig } = require('src/config')568 const mockConfigDefault = createMockConfig()569 const mockConfig = {570 ...mockConfigDefault,571 onTokenRefreshError: undefined,572 }573 expect(() => {574 setConfig(mockConfig)575 }).not.toThrow()576 })577 it('defaults onTokenRefreshError to a function', () => {578 expect.assertions(1)579 const { getConfig, setConfig } = require('src/config')580 const mockConfigDefault = createMockConfig()581 delete mockConfigDefault.onTokenRefreshError582 setConfig(mockConfigDefault)583 const config = getConfig()584 expect(typeof config.onTokenRefreshError).toEqual('function')585 })586 it('throws if onTokenRefreshError is not a function', () => {587 expect.assertions(1)588 const { setConfig } = require('src/config')589 const mockConfigDefault = createMockConfig()590 const mockConfig = {591 ...mockConfigDefault,592 onTokenRefreshError: false,593 }594 expect(() => {595 setConfig(mockConfig)596 }).toThrow(597 'Invalid next-firebase-auth options: The "onTokenRefreshError" setting must be a function.'598 )599 })600})601describe('config: debug logging', () => {602 it('[server-side] logs the config for debugging', () => {603 expect.assertions(1)604 const logDebug = require('src/logDebug').default605 const isClientSide = require('src/isClientSide').default606 isClientSide.mockReturnValue(false)607 const { setConfig } = require('src/config')608 const mockConfig = createMockConfig()609 setConfig(mockConfig)610 const expectedConfig = {611 ...mockConfig,612 onVerifyTokenError: expect.any(Function),613 onTokenRefreshError: expect.any(Function),614 cookies: {615 ...mockConfig.cookies,616 keys: ['hidden'],617 },618 firebaseAdminInitConfig: {619 ...mockConfig.firebaseAdminInitConfig,620 credential: {621 ...mockConfig.firebaseAdminInitConfig.credential,622 privateKey: 'hidden',623 clientEmail: 'hidden',624 },625 },626 }627 expect(logDebug).toHaveBeenCalledWith(628 'Setting config with provided value:',629 expectedConfig630 )631 })632 // For usage with the useFirebaseAdminDefaultCredential setting:633 // https://github.com/gladly-team/next-firebase-auth/issues/434634 it('[server-side] does not throw an error if the firebaseAdminInitConfig is not set', () => {635 expect.assertions(1)636 const isClientSide = require('src/isClientSide').default637 isClientSide.mockReturnValue(false)638 const { setConfig } = require('src/config')639 const mockConfig = {640 ...createMockConfig(),641 firebaseAdminInitConfig: undefined,642 useFirebaseAdminDefaultCredential: true,643 }644 expect(() => {645 setConfig(mockConfig)646 }).not.toThrow()647 })648 it('[server-side] ignores an unset firebaseAdminInitConfig value when logging for debugging', () => {649 expect.assertions(1)650 const logDebug = require('src/logDebug').default651 const isClientSide = require('src/isClientSide').default652 isClientSide.mockReturnValue(false)653 const { setConfig } = require('src/config')654 const mockConfig = {655 ...createMockConfig(),656 firebaseAdminInitConfig: undefined,657 useFirebaseAdminDefaultCredential: true,658 }659 setConfig(mockConfig)660 const expectedConfig = {661 ...mockConfig,662 onVerifyTokenError: expect.any(Function),663 onTokenRefreshError: expect.any(Function),664 cookies: {665 ...mockConfig.cookies,666 keys: ['hidden'],667 },668 firebaseAdminInitConfig: undefined,669 }670 expect(logDebug).toHaveBeenCalledWith(671 'Setting config with provided value:',672 expectedConfig673 )674 })675 it('[server-side] ignores an unset firebaseAdminInitConfig.credential value when logging for debugging', () => {676 expect.assertions(1)677 const logDebug = require('src/logDebug').default678 const isClientSide = require('src/isClientSide').default679 isClientSide.mockReturnValue(false)680 const { setConfig } = require('src/config')681 const mockConfig = {682 ...createMockConfig(),683 firebaseAdminInitConfig: {684 databaseURL: 'some-database-url-here',685 },686 useFirebaseAdminDefaultCredential: true,687 }688 setConfig(mockConfig)689 const expectedConfig = {690 ...mockConfig,691 onVerifyTokenError: expect.any(Function),692 onTokenRefreshError: expect.any(Function),693 cookies: {694 ...mockConfig.cookies,695 keys: ['hidden'],696 },697 firebaseAdminInitConfig: {698 databaseURL: 'some-database-url-here',699 },700 }701 expect(logDebug).toHaveBeenCalledWith(702 'Setting config with provided value:',...
currency_spec.js
Source:currency_spec.js
...18 fakeCurrencyFileServer = sinon.fakeServer.create();19 });20 afterEach(function () {21 fakeCurrencyFileServer.restore();22 setConfig({});23 });24 describe('setConfig', function () {25 beforeEach(function() {26 sandbox = sinon.sandbox.create();27 clock = sinon.useFakeTimers(1046952000000); // 2003-03-06T12:00:00Z28 });29 afterEach(function () {30 sandbox.restore();31 clock.restore();32 });33 it('results in currencySupportEnabled = false when currency not configured', function () {34 setConfig({});35 expect(currencySupportEnabled).to.equal(false);36 });37 it('results in currencySupportEnabled = true and currencyRates being loaded when configured', function () {38 fakeCurrencyFileServer.respondWith(JSON.stringify(getCurrencyRates()));39 setConfig({ 'adServerCurrency': 'JPY' });40 fakeCurrencyFileServer.respond();41 expect(currencyRates.dataAsOf).to.equal('2017-04-25');42 expect(currencySupportEnabled).to.equal(true);43 });44 it('currency file is called even when default rates are specified', function() {45 // RESET to request currency file (specifically url value for this test)46 setConfig({ 'adServerCurrency': undefined });47 // DO NOT SET DEFAULT RATES, currency file should be requested48 setConfig({49 'adServerCurrency': 'JPY'50 });51 fakeCurrencyFileServer.respond();52 expect(fakeCurrencyFileServer.requests.length).to.equal(1);53 expect(fakeCurrencyFileServer.requests[0].url).to.equal('https://cdn.jsdelivr.net/gh/prebid/currency-file@1/latest.json?date=20030306');54 // RESET to request currency file (specifically url value for this test)55 setConfig({ 'adServerCurrency': undefined });56 // SET DEFAULT RATES, currency file should STILL be requested57 setConfig({58 'adServerCurrency': 'JPY',59 'defaultRates': {60 'GBP': { 'CNY': 66, 'JPY': 132, 'USD': 264 },61 'USD': { 'CNY': 60, 'GBP': 120, 'JPY': 240 }62 } });63 fakeCurrencyFileServer.respond();64 expect(fakeCurrencyFileServer.requests.length).to.equal(2);65 expect(fakeCurrencyFileServer.requests[1].url).to.equal('https://cdn.jsdelivr.net/gh/prebid/currency-file@1/latest.json?date=20030306');66 });67 it('date macro token $$TODAY$$ is replaced by current date (formatted as yyyymmdd)', function () {68 // RESET to request currency file (specifically url value for this test)69 setConfig({ 'adServerCurrency': undefined });70 // date macro should replace $$TODAY$$ with date when DEFAULT_CURRENCY_RATE_URL is used71 setConfig({ 'adServerCurrency': 'JPY' });72 fakeCurrencyFileServer.respond();73 expect(fakeCurrencyFileServer.requests[0].url).to.equal('https://cdn.jsdelivr.net/gh/prebid/currency-file@1/latest.json?date=20030306');74 // RESET to request currency file (specifically url value for this test)75 setConfig({ 'adServerCurrency': undefined });76 // date macro should not modify 'conversionRateFile' if TOKEN is not found77 setConfig({78 'adServerCurrency': 'JPY',79 'conversionRateFile': 'http://test.net/currency.json?date=foobar'80 });81 fakeCurrencyFileServer.respond();82 expect(fakeCurrencyFileServer.requests[1].url).to.equal('http://test.net/currency.json?date=foobar');83 // RESET to request currency file (specifically url value for this test)84 setConfig({ 'adServerCurrency': undefined });85 // date macro should replace $$TODAY$$ with date for 'conversionRateFile' is configured86 setConfig({87 'adServerCurrency': 'JPY',88 'conversionRateFile': 'http://test.net/currency.json?date=$$TODAY$$'89 });90 fakeCurrencyFileServer.respond();91 expect(fakeCurrencyFileServer.requests[2].url).to.equal('http://test.net/currency.json?date=20030306');92 // RESET to request currency file (specifically url value for this test)93 setConfig({ 'adServerCurrency': undefined });94 // MULTIPLE TOKENS used in a url is not supported. Only the TOKEN at left-most position is REPLACED95 setConfig({96 'adServerCurrency': 'JPY',97 'conversionRateFile': 'http://test.net/$$TODAY$$/currency.json?date=$$TODAY$$'98 });99 fakeCurrencyFileServer.respond();100 expect(fakeCurrencyFileServer.requests[3].url).to.equal('http://test.net/20030306/currency.json?date=$$TODAY$$');101 });102 });103 describe('bidder override', function () {104 it('allows setConfig to set bidder currency', function () {105 setConfig({});106 var bid = { cpm: 1, bidder: 'rubicon' };107 var innerBid;108 setConfig({109 adServerCurrency: 'GBP',110 bidderCurrencyDefault: {111 rubicon: 'GBP'112 }113 });114 addBidResponseHook(function(adCodeId, bid) {115 innerBid = bid;116 }, 'elementId', bid);117 expect(innerBid.currency).to.equal('GBP');118 expect(typeof innerBid.getCpmInNewCurrency).to.equal('function');119 expect(innerBid.getCpmInNewCurrency('GBP')).to.equal('1.000');120 });121 it('uses adapter currency over currency override if specified', function () {122 setConfig({});123 var bid = { cpm: 1, currency: 'JPY', bidder: 'rubicon' };124 var innerBid;125 setConfig({126 adServerCurrency: 'JPY',127 bidderCurrencyDefault: {128 rubicon: 'GBP'129 }130 });131 addBidResponseHook(function(adCodeId, bid) {132 innerBid = bid;133 }, 'elementId', bid);134 expect(innerBid.currency).to.equal('JPY');135 expect(typeof innerBid.getCpmInNewCurrency).to.equal('function');136 expect(innerBid.getCpmInNewCurrency('JPY')).to.equal('1.000');137 });138 it('uses rates specified in json when provided', function () {139 setConfig({140 adServerCurrency: 'USD',141 rates: {142 USD: {143 JPY: 100144 }145 }146 });147 var bid = { cpm: 100, currency: 'JPY', bidder: 'rubicon' };148 var innerBid;149 addBidResponseHook(function(adCodeId, bid) {150 innerBid = bid;151 }, 'elementId', bid);152 expect(innerBid.cpm).to.equal('1.0000');153 expect(typeof innerBid.getCpmInNewCurrency).to.equal('function');154 expect(innerBid.getCpmInNewCurrency('JPY')).to.equal('100.000');155 });156 it('uses default rates when currency file fails to load', function () {157 setConfig({});158 setConfig({159 adServerCurrency: 'USD',160 defaultRates: {161 USD: {162 JPY: 100163 }164 }165 });166 // default response is 404167 fakeCurrencyFileServer.respond();168 var bid = { cpm: 100, currency: 'JPY', bidder: 'rubicon' };169 var innerBid;170 addBidResponseHook(function(adCodeId, bid) {171 innerBid = bid;172 }, 'elementId', bid);173 expect(innerBid.cpm).to.equal('1.0000');174 expect(typeof innerBid.getCpmInNewCurrency).to.equal('function');175 expect(innerBid.getCpmInNewCurrency('JPY')).to.equal('100.000');176 });177 });178 describe('currency.addBidResponseDecorator bidResponseQueue', function () {179 it('not run until currency rates file is loaded', function () {180 setConfig({});181 fakeCurrencyFileServer.respondWith(JSON.stringify(getCurrencyRates()));182 var bid = { 'cpm': 1, 'currency': 'USD' };183 setConfig({ 'adServerCurrency': 'JPY' });184 var marker = false;185 addBidResponseHook(function() {186 marker = true;187 }, 'elementId', bid);188 expect(marker).to.equal(false);189 fakeCurrencyFileServer.respond();190 expect(marker).to.equal(true);191 });192 });193 describe('currency.addBidResponseDecorator', function () {194 it('should leave bid at 1 when currency support is not enabled and fromCurrency is USD', function () {195 setConfig({});196 var bid = { 'cpm': 1, 'currency': 'USD' };197 var innerBid;198 addBidResponseHook(function(adCodeId, bid) {199 innerBid = bid;200 }, 'elementId', bid);201 expect(innerBid.cpm).to.equal(1);202 });203 it('should result in NO_BID when currency support is not enabled and fromCurrency is not USD', function () {204 setConfig({});205 var bid = { 'cpm': 1, 'currency': 'GBP' };206 var innerBid;207 addBidResponseHook(function(adCodeId, bid) {208 innerBid = bid;209 }, 'elementId', bid);210 expect(innerBid.statusMessage).to.equal('Bid returned empty or error response');211 });212 it('should not buffer bid when currency is already in desired currency', function () {213 setConfig({214 'adServerCurrency': 'USD'215 });216 var bid = { 'cpm': 1, 'currency': 'USD' };217 var innerBid;218 addBidResponseHook(function(adCodeId, bid) {219 innerBid = bid;220 }, 'elementId', bid);221 expect(bid).to.equal(innerBid);222 });223 it('should result in NO_BID when fromCurrency is not supported in file', function () {224 // RESET to request currency file225 setConfig({ 'adServerCurrency': undefined });226 fakeCurrencyFileServer.respondWith(JSON.stringify(getCurrencyRates()));227 setConfig({ 'adServerCurrency': 'JPY' });228 fakeCurrencyFileServer.respond();229 var bid = { 'cpm': 1, 'currency': 'ABC' };230 var innerBid;231 addBidResponseHook(function(adCodeId, bid) {232 innerBid = bid;233 }, 'elementId', bid);234 expect(innerBid.statusMessage).to.equal('Bid returned empty or error response');235 });236 it('should result in NO_BID when adServerCurrency is not supported in file', function () {237 fakeCurrencyFileServer.respondWith(JSON.stringify(getCurrencyRates()));238 setConfig({ 'adServerCurrency': 'ABC' });239 fakeCurrencyFileServer.respond();240 var bid = { 'cpm': 1, 'currency': 'GBP' };241 var innerBid;242 addBidResponseHook(function(adCodeId, bid) {243 innerBid = bid;244 }, 'elementId', bid);245 expect(innerBid.statusMessage).to.equal('Bid returned empty or error response');246 });247 it('should return 1 when currency support is enabled and same currency code is requested as is set to adServerCurrency', function () {248 fakeCurrencyFileServer.respondWith(JSON.stringify(getCurrencyRates()));249 setConfig({ 'adServerCurrency': 'JPY' });250 fakeCurrencyFileServer.respond();251 var bid = { 'cpm': 1, 'currency': 'JPY' };252 var innerBid;253 addBidResponseHook(function(adCodeId, bid) {254 innerBid = bid;255 }, 'elementId', bid);256 expect(innerBid.cpm).to.equal(1);257 expect(innerBid.currency).to.equal('JPY');258 });259 it('should return direct conversion rate when fromCurrency is one of the configured bases', function () {260 fakeCurrencyFileServer.respondWith(JSON.stringify(getCurrencyRates()));261 setConfig({ 'adServerCurrency': 'GBP' });262 fakeCurrencyFileServer.respond();263 var bid = { 'cpm': 1, 'currency': 'USD' };264 var innerBid;265 addBidResponseHook(function(adCodeId, bid) {266 innerBid = bid;267 }, 'elementId', bid);268 expect(innerBid.cpm).to.equal('0.7798');269 expect(innerBid.currency).to.equal('GBP');270 });271 it('should return reciprocal conversion rate when adServerCurrency is one of the configured bases, but fromCurrency is not', function () {272 fakeCurrencyFileServer.respondWith(JSON.stringify(getCurrencyRates()));273 setConfig({ 'adServerCurrency': 'GBP' });274 fakeCurrencyFileServer.respond();275 var bid = { 'cpm': 1, 'currency': 'CNY' };276 var innerBid;277 addBidResponseHook(function(adCodeId, bid) {278 innerBid = bid;279 }, 'elementId', bid);280 expect(innerBid.cpm).to.equal('0.1133');281 expect(innerBid.currency).to.equal('GBP');282 });283 it('should return intermediate conversion rate when neither fromCurrency nor adServerCurrency is one of the configured bases', function () {284 fakeCurrencyFileServer.respondWith(JSON.stringify(getCurrencyRates()));285 setConfig({ 'adServerCurrency': 'CNY' });286 fakeCurrencyFileServer.respond();287 var bid = { 'cpm': 1, 'currency': 'JPY' };288 var innerBid;289 addBidResponseHook(function(adCodeId, bid) {290 innerBid = bid;291 }, 'elementId', bid);292 expect(innerBid.cpm).to.equal('0.0623');293 expect(innerBid.currency).to.equal('CNY');294 });295 });...
number-input.component.spec.js
Source:number-input.component.spec.js
...48 });49 });50 describe('increaseValue(): ', function () {51 it('should increase current value when current value is empty', function () {52 setConfig(4, 10, 1);53 ctrl.increaseValue();54 expect(ctrl.currentValue).toEqual(4);55 setConfig(-8, -2, 1);56 ctrl.increaseValue();57 expect(ctrl.currentValue).toEqual(-2);58 setConfig(-4, 1, 2);59 ctrl.increaseValue();60 expect(ctrl.currentValue).toEqual(1);61 setConfig(2, 10, 3);62 ctrl.increaseValue();63 expect(ctrl.currentValue).toEqual(3);64 setConfig(0, 10, 1);65 ctrl.increaseValue();66 expect(ctrl.currentValue).toEqual(1);67 setConfig(-2, 2, 5);68 ctrl.increaseValue();69 expect(ctrl.currentValue).toEqual(2);70 setConfig(0, 1, 1);71 ctrl.increaseValue();72 expect(ctrl.currentValue).toEqual(1);73 });74 it('should increase current value when current value is settled', function () {75 setConfig(0, 10, 1, -3);76 ctrl.increaseValue();77 expect(ctrl.currentValue).toEqual(0);78 setConfig(4, 10, 1, 14);79 ctrl.increaseValue();80 expect(ctrl.currentValue).toEqual(14);81 setConfig(-4, 3, 2, 2);82 ctrl.increaseValue();83 expect(ctrl.currentValue).toEqual(3);84 setConfig(2, 10, 3, 1);85 ctrl.increaseValue();86 expect(ctrl.currentValue).toEqual(4);87 setConfig(0, 10, 1, 0);88 ctrl.increaseValue();89 expect(ctrl.currentValue).toEqual(1);90 setConfig(-2, 2, 5, -1);91 ctrl.increaseValue();92 expect(ctrl.currentValue).toEqual(2);93 });94 });95 describe('decreaseValue(): ', function () {96 it('should decrease current value when current value is empty', function () {97 setConfig(0, 10, 1);98 ctrl.decreaseValue();99 expect(ctrl.currentValue).toEqual(0);100 setConfig(4, 10, 1);101 ctrl.decreaseValue();102 expect(ctrl.currentValue).toEqual(4);103 setConfig(-8, -2, 1);104 ctrl.decreaseValue();105 expect(ctrl.currentValue).toEqual(-2);106 setConfig(-2, 10, 3);107 ctrl.decreaseValue();108 expect(ctrl.currentValue).toEqual(-2);109 setConfig(-8, -1, 2);110 ctrl.decreaseValue();111 expect(ctrl.currentValue).toEqual(-2);112 setConfig(-2, 2, 1);113 ctrl.decreaseValue();114 expect(ctrl.currentValue).toEqual(-1);115 setConfig(-2, 2, 5);116 ctrl.decreaseValue();117 expect(ctrl.currentValue).toEqual(-2);118 setConfig(-2, 2, 2);119 ctrl.decreaseValue();120 expect(ctrl.currentValue).toEqual(-2);121 });122 it('should decrease current value when current value is settled', function () {123 setConfig(0, 10, 1, -3);124 ctrl.decreaseValue();125 expect(ctrl.currentValue).toEqual(-3);126 setConfig(4, 10, 1, 14);127 ctrl.decreaseValue();128 expect(ctrl.currentValue).toEqual(10);129 setConfig(-4, -1, 2, -3);130 ctrl.decreaseValue();131 expect(ctrl.currentValue).toEqual(-4);132 setConfig(2, 10, 3, 12);133 ctrl.decreaseValue();134 expect(ctrl.currentValue).toEqual(9);135 setConfig(0, 10, 1, 5);136 ctrl.decreaseValue();137 expect(ctrl.currentValue).toEqual(4);138 setConfig(-2, 2, 5, 1);139 ctrl.decreaseValue();140 expect(ctrl.currentValue).toEqual(-2);141 });142 });143 describe('isShownUnit(): ', function () {144 it('should return true', function () {145 var componentScopeUnitValue;146 componentScopeUnitValue = ctrl.isShownUnit(ctrl.suffixUnit);147 expect(componentScopeUnitValue).toBeTruthy();148 });149 it('should return false', function () {150 var componentScopeUnitValue;151 ctrl.suffixUnit = undefined;152 componentScopeUnitValue = ctrl.isShownUnit(ctrl.suffixUnit);153 expect(componentScopeUnitValue).toBeFalsy();154 });155 });156 describe('isValid(): ', function () {157 beforeEach(function () {158 ctrl.formObject = {159 'input_name': {160 $setValidity: angular.noop161 }162 };163 ctrl.inputName = 'input_name';164 });165 it('should call isShowFieldInvalidState method', function () {166 spyOn(ctrl, 'isShowFieldInvalidState').and.returnValue(true);167 ctrl.currentValue = '1';168 ctrl.isValid();169 expect(ctrl.isShowFieldInvalidState).toHaveBeenCalled();170 });171 it('should not call isShowFieldInvalidState method and should return true if ctrl.allowEmptyField is false', function () {172 spyOn(ctrl, 'isShowFieldInvalidState').and.returnValue(true);173 expect(ctrl.isShowFieldInvalidState).not.toHaveBeenCalled();174 });175 });176 function setConfig(min, max, step, cv) {177 ctrl.minValue = min;178 ctrl.maxValue = max;179 ctrl.valueStep = step;180 ctrl.currentValue = cv;181 ctrl.$onInit();182 }...
config_spec.js
Source:config_spec.js
...26 it('getConfig returns an object', function () {27 expect(getConfig()).to.be.a('object');28 });29 it('sets and gets arbitrary configuarion properties', function () {30 setConfig({ baz: 'qux' });31 expect(getConfig('baz')).to.equal('qux');32 });33 it('only accepts objects', function () {34 setConfig('invalid');35 expect(getConfig('0')).to.not.equal('i');36 });37 it('sets multiple config properties', function () {38 setConfig({ foo: 'bar' });39 setConfig({ biz: 'buz' });40 var config = getConfig();41 expect(config.foo).to.equal('bar');42 expect(config.biz).to.equal('buz');43 });44 it('overwrites existing config properties', function () {45 setConfig({ foo: {biz: 'buz'} });46 setConfig({ foo: {baz: 'qux'} });47 expect(getConfig('foo')).to.eql({baz: 'qux'});48 });49 it('sets debugging', function () {50 setConfig({ debug: true });51 expect(getConfig('debug')).to.be.true;52 });53 it('sets bidderTimeout', function () {54 setConfig({ bidderTimeout: 1000 });55 expect(getConfig('bidderTimeout')).to.be.equal(1000);56 });57 it('gets user-defined publisherDomain', function () {58 setConfig({ publisherDomain: 'fc.kahuna' });59 expect(getConfig('publisherDomain')).to.equal('fc.kahuna');60 });61 it('gets default userSync config', function () {62 const DEFAULT_USERSYNC = {63 syncEnabled: true,64 pixelEnabled: true,65 syncsPerBidder: 5,66 syncDelay: 300067 };68 setDefaults({'userSync': DEFAULT_USERSYNC});69 expect(getConfig('userSync')).to.eql(DEFAULT_USERSYNC);70 });71 it('has subscribe functionality for adding listeners to config updates', function () {72 const listener = sinon.spy();73 getConfig(listener);74 setConfig({ foo: 'bar' });75 sinon.assert.calledOnce(listener);76 sinon.assert.calledWith(listener, { foo: 'bar' });77 });78 it('subscribers can unsubscribe', function () {79 const listener = sinon.spy();80 const unsubscribe = getConfig(listener);81 unsubscribe();82 setConfig({ logging: true });83 sinon.assert.notCalled(listener);84 });85 it('subscribers can subscribe to topics', function () {86 const listener = sinon.spy();87 getConfig('logging', listener);88 setConfig({ logging: true, foo: 'bar' });89 sinon.assert.calledOnce(listener);90 sinon.assert.calledWithExactly(listener, { logging: true });91 });92 it('topic subscribers are only called when that topic is changed', function () {93 const listener = sinon.spy();94 const wildcard = sinon.spy();95 getConfig('subject', listener);96 getConfig(wildcard);97 setConfig({ foo: 'bar' });98 sinon.assert.notCalled(listener);99 sinon.assert.calledOnce(wildcard);100 });101 it('sets priceGranularity', function () {102 setConfig({ priceGranularity: 'low' });103 expect(getConfig('priceGranularity')).to.be.equal('low');104 });105 it('set mediaTypePriceGranularity', function () {106 const customPriceGranularity = {107 'buckets': [{108 'min': 0,109 'max': 3,110 'increment': 0.01,111 'cap': true112 }]113 };114 setConfig({115 'mediaTypePriceGranularity': {116 'banner': 'medium',117 'video': customPriceGranularity,118 'native': 'medium'119 }120 });121 const configResult = getConfig('mediaTypePriceGranularity');122 expect(configResult.banner).to.be.equal('medium');123 expect(configResult.video).to.be.equal(customPriceGranularity);124 expect(configResult.native).to.be.equal('medium');125 });126 it('sets priceGranularity and customPriceBucket', function () {127 const goodConfig = {128 'buckets': [{129 'min': 0,130 'max': 3,131 'increment': 0.01,132 'cap': true133 }]134 };135 setConfig({ priceGranularity: goodConfig });136 expect(getConfig('priceGranularity')).to.be.equal('custom');137 expect(getConfig('customPriceBucket')).to.equal(goodConfig);138 });139 it('should log error for invalid priceGranularity', function () {140 setConfig({ priceGranularity: '' });141 const error = 'Prebid Error: no value passed to `setPriceGranularity()`';142 assert.ok(logErrorSpy.calledWith(error), 'expected error was logged');143 });144 it('should log a warning on invalid values', function () {145 setConfig({ bidderSequence: 'unrecognized sequence' });146 expect(logWarnSpy.calledOnce).to.equal(true);147 });148 it('should not log warnings when given recognized values', function () {149 setConfig({ bidderSequence: 'fixed' });150 setConfig({ bidderSequence: 'random' });151 expect(logWarnSpy.called).to.equal(false);152 });...
test.modal.js
Source:test.modal.js
...6describe('ax5.ui.modal.setConfig TEST', function () {7 var myModal;8 before(function () {9 myModal = new ax5.ui.modal();10 myModal.setConfig({11 width: 100,12 height: 200,13 position: {14 left: 'left',15 top: "top",16 margin: "10"17 },18 iframeLoadingMsg: "loading",19 iframe: {20 method: "get",21 url: "",22 param: {}23 },24 closeToEsc: true,...
posts.js
Source:posts.js
...16};17const getSubPosts = async (limit, page) => {18 const response = await axios.get(19 `${baseUrl}/subscribed/?limit=${limit}&page=${page}`,20 setConfig()21 );22 return response.data;23};24const getSearchResults = async (query, limit, page) => {25 const response = await axios.get(26 `${baseUrl}/search/?query=${query}&limit=${limit}&page=${page}`27 );28 return response.data;29};30const addNew = async (postObj) => {31 const response = await axios.post(`${baseUrl}`, postObj, setConfig());32 return response.data;33};34const editPost = async (id, postObj) => {35 const response = await axios.patch(`${baseUrl}/${id}`, postObj, setConfig());36 return response.data;37};38const getPostComments = async (id) => {39 const response = await axios.get(`${baseUrl}/${id}/comments`);40 return response.data;41};42const upvotePost = async (id) => {43 const response = await axios.post(44 `${baseUrl}/${id}/upvote`,45 null,46 setConfig()47 );48 return response.data;49};50const downvotePost = async (id) => {51 const response = await axios.post(52 `${baseUrl}/${id}/downvote`,53 null,54 setConfig()55 );56 return response.data;57};58const deletePost = async (id) => {59 const response = await axios.delete(`${baseUrl}/${id}`, setConfig());60 return response.data;61};62const upvoteComment = async (postId, commentId) => {63 const response = await axios.post(64 `${baseUrl}/${postId}/comment/${commentId}/upvote`,65 null,66 setConfig()67 );68 return response.data;69};70const downvoteComment = async (postId, commentId) => {71 const response = await axios.post(72 `${baseUrl}/${postId}/comment/${commentId}/downvote`,73 null,74 setConfig()75 );76 return response.data;77};78const upvoteReply = async (postId, commentId, replyId) => {79 const response = await axios.post(80 `${baseUrl}/${postId}/comment/${commentId}/reply/${replyId}/upvote`,81 null,82 setConfig()83 );84 return response.data;85};86const downvoteReply = async (postId, commentId, replyId) => {87 const response = await axios.post(88 `${baseUrl}/${postId}/comment/${commentId}/reply/${replyId}/downvote`,89 null,90 setConfig()91 );92 return response.data;93};94const postComment = async (postId, commentObj) => {95 const response = await axios.post(96 `${baseUrl}/${postId}/comment`,97 commentObj,98 setConfig()99 );100 return response.data;101};102const postReply = async (postId, commentId, replyObj) => {103 const response = await axios.post(104 `${baseUrl}/${postId}/comment/${commentId}/reply`,105 replyObj,106 setConfig()107 );108 return response.data;109};110const updateComment = async (postId, commentId, commentObj) => {111 const response = await axios.patch(112 `${baseUrl}/${postId}/comment/${commentId}`,113 commentObj,114 setConfig()115 );116 return response.data;117};118const removeComment = async (postId, commentId) => {119 const response = await axios.delete(120 `${baseUrl}/${postId}/comment/${commentId}`,121 setConfig()122 );123 return response.data;124};125const updateReply = async (postId, commentId, replyId, replyObj) => {126 const response = await axios.patch(127 `${baseUrl}/${postId}/comment/${commentId}/reply/${replyId}`,128 replyObj,129 setConfig()130 );131 return response.data;132};133const removeReply = async (postId, commentId, replyId) => {134 const response = await axios.delete(135 `${baseUrl}/${postId}/comment/${commentId}/reply/${replyId}`,136 setConfig()137 );138 return response.data;139};140const postService = {141 getPosts,142 getSubPosts,143 getSearchResults,144 addNew,145 editPost,146 getPostComments,147 upvotePost,148 downvotePost,149 deletePost,150 upvoteComment,...
config.js
Source:config.js
...28 ],29 function () {30 //>>excludeEnd("tauBuildExclude");31 // Default configuration properties32 ns.setConfig("rootDir", ns.getFrameworkPath(), true);33 ns.setConfig("version", "", true);34 ns.setConfig("allowCrossDomainPages", false, true);35 ns.setConfig("domCache", false, true);36 // .. other possible options37 ns.setConfig("autoBuildOnPageChange", true, true);38 ns.setConfig("autoInitializePage", true, true);39 ns.setConfig("dynamicBaseEnabled", true, true);40 ns.setConfig("pageTransition", "none", true);41 ns.setConfig("popupTransition", "none", true);42 ns.setConfig("popupFullSize", false, true);43 ns.setConfig("scrollEndEffectArea", "content", true);44 ns.setConfig("enablePopupScroll", false, true);45 // ns.setConfig('container', document.body); // for defining application container46 // same as above, but for wearable version47 ns.setConfig("pageContainer", document.body, true);48 ns.setConfig("findProfileFile", false, true);49 ns.setConfig("keyboardSupport", false);50 //>>excludeStart("tauBuildExclude", pragmas.tauBuildExclude);51 }52 );53 //>>excludeEnd("tauBuildExclude");...
Using AI Code Generation
1Cypress.config('baseUrl', null)2{3}4{5}6{7 "env": {8 }9}10{11 "env": {12 }13}14{15 "env": {16 }17}18{19 "env": {20 }21}22{23 "env": {24 }25}26{27 "env": {28 }29}30{31 "env": {32 }33}34{35 "env": {36 }37}38{39 "env": {40 }41}42{43 "env": {44 }45}
Using AI Code Generation
1describe("Test", function () {2 before(() => {3 cy.setConfig({4 });5 });6 it("Test", function () {7 });8});9[MIT](
Using AI Code Generation
1{2}3{4 "env": {5 }6}7{8}9{10}11{12}13{14}15{16}17{18}19{20}21{22}23{24}25{26}
Using AI Code Generation
1describe('My First Test Suite', function() 2{3 it('My FirstTest case',function() {4 cy.visit("/")5 cy.get('#alertbtn').click()6 cy.on('window:alert',(str)=>7 {8 expect(str).to.equal('Hello , share this practice page and share your knowledge')9 })10 cy.get('#confirmbtn').click()11 cy.on('window:confirm',(str)=>12 {13 expect(str).to.equal('Hello , Are you sure you want to confirm?')14 })15 })16})
Using AI Code Generation
1### `Cypress.env()`2### `Cypress.on()`3Cypress.on('test:before:run', (test, runnable) => {4})5Cypress.on('test:after:run', (test, runnable) => {6})7### `Cypress.off()`8Cypress.off('test:before:run', (test, runnable) => {9})10Cypress.off('test:after:run', (test, runnable) => {11})12### `Cypress.once()`13Cypress.once('test:before:run', (test, runnable) => {14})15Cypress.once('test:after:run', (test, runnable) => {16})17### `Cypress.removeListener()`18Cypress.removeListener('test:before:run', (test, runnable) => {19})20Cypress.removeListener('test:after:run
Using AI Code Generation
1Cypress.config('defaultCommandTimeout', 10000)2Cypress.config('requestTimeout', 10000)3Cypress.config('responseTimeout', 10000)4Cypress.config('viewportWidth', 1280)5Cypress.config('viewportHeight', 720)6Cypress.config('viewportWidth', 1280)7Cypress.config('viewportHeight', 720)8Cypress.config('viewportWidth', 1280)9Cypress.config('viewportHeight', 720)10Cypress.config('viewport', 'mac
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!!