How to use currentTestInfo method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Test.View.js

Source:Test.View.js Github

copy

Full Screen

1import { Button, Container, Grid } from '@material-ui/core';2import { useTheme } from '@material-ui/core/styles';3import useMediaQuery from '@material-ui/core/useMediaQuery';4import { Done, Lock as LockIcon, PlayArrow } from '@material-ui/icons';5import React, { useEffect, useState } from 'react';6import { getTestInfoByAppId, setTestInfoPlaying, endTest, getTopicsByParentId, getTestInfoByAppIdAndParentId } from "../../redux/actions/index";7import SelectStatePopup from '../../components/SelectStatePopup';8import { LoadingWidget } from '../../components/Widgets';9import Config from '../../config';10import CloseIcon from '@material-ui/icons/Close';11import { scrollToTop } from '../../models/Utils';12import ReactGA from 'react-ga';13import { connect } from 'react-redux';14import Header from "../../components/Header"15import { AlertDialogSlide, DialogInfo, ShowImage } from '../../components/Dialog';16import { ButtonLevel, TestProgressPanel, TestQuestionPanel } from './TestComponent';17import EndTestView from "./EndTest";18import ArrowRightAltIcon from '@material-ui/icons/ArrowRightAlt';19import SelectTopicPopUp from '../../components/SelectTopicPopUp';20import Footer from '../../components/Footer';21import { CongratulationAlert } from "../game/Game.ViewTS"22const TestViewScreen = ({ appInfoState, topicId = -1 }) => {23 const theme = useTheme()24 const isMobile = useMediaQuery(theme.breakpoints.down('sm'));25 useEffect(() => {26 if (isMobile) {27 scrollToTop();28 }29 }, [isMobile]);30 let appInfo = appInfoState;31 useEffect(() => {32 ReactGA.pageview('/testpage/' + appInfo.title);33 }, []);34 if (!appInfo) {35 return React.createElement(LoadingWidget, null);36 }37 return (38 <TestView appInfoState={appInfoState} topicId={topicId}></TestView>39 )40};41const TestViewUI = ({ stateInfoState, testInfoState, appInfoState, getTestInfoByAppId = () => { }, gameState, getTestInfoByAppIdAndParentId = () => { }, setTestInfoPlaying = () => { }, endTest, getTopicsByParentId }) => {42 let loading = gameState.isLoading === 2;43 const [dialogInfo, setDialogInfo] = useState(DialogInfo.init());44 const [selectedState, setSelectedState] = useState(true);45 const [openPopupChangeState, setOpenPopupChangeState] = useState(false);46 const [currentTestInfo, setCurrentTestInfo] = useState(null);47 const [showGame, setShowGame] = useState(false);48 const [openSelectTopic, setOpenSelectTopic] = useState(false);49 const theme = useTheme();50 const [showLeftPanel, setShowLeftPanel] = useState(false);51 const isMobile = useMediaQuery(theme.breakpoints.between(0, 780));52 let isHaveRightPanel = !((gameState.isFinish && loading) || (gameState.currentQuestion && loading) || (gameState.level < 0));53 useEffect(() => {54 if (Config.LISTBUCKET.indexOf(appInfoState.bucket) !== -1) {55 if (testInfoState.currentTopic[appInfoState.id]) {56 getTestInfoByAppIdAndParentId(appInfoState.id)57 } else {58 return59 }60 } else {61 if (appInfoState.hasState) {62 if (stateInfoState.mapCurrentStateInfo[appInfoState.id]) {63 getTestInfoByAppId(appInfoState.id, stateInfoState.mapCurrentStateInfo[appInfoState.id].id);64 getTopicsByParentId(stateInfoState.mapCurrentStateInfo[appInfoState.id].id);65 }66 } else {67 getTestInfoByAppId(appInfoState.id);68 getTopicsByParentId(appInfoState.id);69 }70 }71 }, [appInfoState.id, getTestInfoByAppId, setTestInfoPlaying, setCurrentTestInfo, getTestInfoByAppIdAndParentId, testInfoState.currentTopic[appInfoState.id], stateInfoState.mapCurrentStateInfo[appInfoState.id]]);72 if (isMobile) {73 return (74 <div className="body-panel test-page">75 <Container className="test-game-panel">76 {showGame ?77 <>78 {(gameState.isFinish && gameState.isLoading === 7 && !showLeftPanel) ? <EndTestView setShowLeftPanel={() => setShowLeftPanel(true)} bucket={appInfoState.bucket}></EndTestView>79 : null}80 <Grid item xs={12} sm={12} md={7} lg={8} className="right-panel" style={{ display: isHaveRightPanel && !showLeftPanel && gameState.isLoading !== 7 ? "block" : "none" }}>81 <div className="box-question-panel">82 {gameState.isFinish ? null : <TestProgressPanel setShowLeftPanel={() => setShowLeftPanel(true)} appInfo={appInfoState}></TestProgressPanel>}83 <TestQuestionPanel84 className="question-view-study-game"85 testInfoId={currentTestInfo.id}86 appId={appInfoState.id}87 timeTest={currentTestInfo.timeTest}88 passPercent={currentTestInfo.passPercent}89 questionIds={currentTestInfo.questionIds}90 appInfoState={appInfoState}91 showLeftPanel={showLeftPanel}92 setShowLeftPanel={() => setShowLeftPanel(true)}93 ></TestQuestionPanel>94 </div>95 </Grid>96 <ButtonLevel97 isHaveRightPanel={isHaveRightPanel}98 testInfoId={currentTestInfo ? currentTestInfo.id : -1}99 appId={appInfoState.id}100 timeTest={currentTestInfo.timeTest}101 passPercent={currentTestInfo.passPercent}102 questionIds={currentTestInfo.questionIds}103 setDialogInfo={setDialogInfo}104 gameStateId={gameState.id}105 level={gameState.level}106 showLeftPanel={showLeftPanel}107 setShowLeftPanel={() => setShowLeftPanel(false)}108 isFinish={gameState.isFinish}109 setShowGame={() => setShowGame(false)}>110 </ButtonLevel>111 </> : (112 <>113 <div style={{ display: "flex", justifyContent: "center" }}>114 {appInfoState.hasState ? <Button115 variant="contained"116 color="primary"117 style={{ background: "#8496EA", color: "#fff", marginTop: isMobile ? "16px" : "", borderRadius: "20px", marginBottom: "16px", display: "block", marginRight: "16px" }}118 onClick={() => setOpenPopupChangeState(true)}119 >Change State</Button> : null}120 {Config.LISTBUCKET.indexOf(appInfoState.bucket) !== -1 ? <Button121 variant="contained"122 color="primary"123 style={{ background: "#8496EA", color: "#fff", marginTop: isMobile ? "16px" : "", borderRadius: "20px", marginBottom: "16px", display: "block", marginRight: "16px" }}124 onClick={() => setOpenSelectTopic(true)}125 >Change Topic</Button> : null}126 </div>127 <ListTestInfo appId={appInfoState.id}128 onChangeTestInfo={(testInfo) => {129 if (!testInfo.playing) {130 setCurrentTestInfo(testInfo);131 if (currentTestInfo) {132 setTestInfoPlaying(currentTestInfo.id, testInfo.id)133 }134 }135 setShowGame(true);136 }}137 level={gameState.level}138 bucket={appInfoState.bucket}>139 </ListTestInfo>140 </>141 )}142 {((Config.LISTBUCKET.indexOf(appInfoState.bucket) !== -1 && !testInfoState.currentTopic[appInfoState.id]) || openSelectTopic === true) ?143 <SelectTopicPopUp appInfoState={appInfoState}144 openSelectTopic={openSelectTopic}145 setOpenSelectTopic={() => setOpenSelectTopic(false)}>146 </SelectTopicPopUp> : null}147 {appInfoState && appInfoState.hasState ?148 <SelectStatePopup149 onLoaded={(selectedState) => {150 setSelectedState(selectedState)151 }}152 openDefault={false}153 appInfo={appInfoState}154 openPopupChangeState={openPopupChangeState}155 onHidden={() => {156 setOpenPopupChangeState(false);157 setOpenSelectTopic(true);158 }} /> : ''}159 </Container>160 {showGame ? null : <Footer isStudy={true}></Footer>}161 </div>162 )163 }164 return (165 <div className="body-panel test-page">166 <Header isStudy={true} appInfo={appInfoState}></Header>167 <Container className="test-game-panel">168 {dialogInfo ? <AlertDialogSlide dialogInfo={dialogInfo} /> : ''}169 {showGame ? (170 <>171 <ButtonLevel testInfoId={currentTestInfo ? currentTestInfo.id : -1}172 appId={appInfoState.id}173 timeTest={currentTestInfo ? currentTestInfo.timeTest : -1}174 passPercent={currentTestInfo ? currentTestInfo.passPercent : -1}175 questionIds={currentTestInfo ? currentTestInfo.questionIds : null}176 setDialogInfo={setDialogInfo}177 gameStateId={gameState.id}178 level={gameState.level}179 setShowLeftPanel={() => setShowLeftPanel(false)}180 isFinish={gameState.isFinish}181 setShowGame={() => setShowGame(false)}>182 </ButtonLevel>183 <div className="spacer-height-test"></div>184 <Grid185 container186 alignItems="stretch"187 spacing={4}188 style={isHaveRightPanel ? {} : { display: "none" }}189 className="main-test-game-panel"190 >191 <Grid item xs={12} sm={12} md={5} lg={4} className="left-panel border-box">192 {(gameState.isFinish && gameState.isLoading !== 2) ? (193 <EndTestView bucket={appInfoState.bucket}></EndTestView>194 ) : (195 <div className="left-panel-box border-box">196 <div className="left-panel-content">197 <div className="description">198 You are about to take the199 simulator test. If you pass this200 test at least 5 times,201 congratulations! You are ready202 for your real test203 </div>204 <ul className="list-content">205 <li>As close as it gets to the actual test.</li>206 <li>{gameState.questions.length} questions</li>207 <li>{gameState.progress.total - Math.round(gameState.progress.total * gameState.passPercent / 100)} mistakes allowed</li>208 <li>New questions every time you re-take.</li>209 <li>Stop as soon as you have reached the failing score</li>210 </ul>211 </div>212 <Button213 variant="contained"214 color="primary"215 onClick={() => {216 endTest();217 }}218 style={219 {220 display: ((gameState.isFinish && loading) || (gameState.currentQuestion && loading) || (gameState.level < 0)) ? "none" : "block",221 background: "#EF7352",222 boxShadow: "inset 0px 4px 4px rgba(255, 255, 255, 0.25)",223 borderRadius: "20px",224 width: "240px",225 marginLeft: "auto",226 marginRight: "auto"227 }228 }>End Test</Button>229 </div>230 )}231 </Grid>232 <Grid item xs={12} sm={12} md={7} lg={8} className="right-panel border-box">233 <div className="box-question-panel border-box">234 {gameState.isFinish ? null : <TestProgressPanel setShowLeftPanel={() => setShowLeftPanel(true)} appInfo={appInfoState}></TestProgressPanel>}235 <TestQuestionPanel236 className="question-view-study-game border-box"237 testInfoId={currentTestInfo ? currentTestInfo.id : -1}238 appId={appInfoState.id}239 timeTest={currentTestInfo.timeTest}240 passPercent={currentTestInfo.passPercent}241 questionIds={currentTestInfo.questionIds}242 appInfoState={appInfoState}243 ></TestQuestionPanel>244 </div>245 </Grid>246 </Grid>247 </>248 ) : (249 <>250 <div style={{ display: "flex", justifyContent: "center" }}>251 {appInfoState.hasState ? <Button252 variant="contained"253 color="primary"254 style={{ background: "#8496EA", color: "#fff", marginTop: isMobile ? "16px" : "", borderRadius: "20px", marginBottom: "16px", display: "block", marginRight: "16px" }}255 onClick={() => setOpenPopupChangeState(true)}256 >Change State</Button> : null}257 {Config.LISTBUCKET.indexOf(appInfoState.bucket) !== -1 ? <Button258 variant="contained"259 color="primary"260 style={{ background: "#8496EA", color: "#fff", marginTop: isMobile ? "16px" : "", borderRadius: "20px", marginBottom: "16px", display: "block" }}261 onClick={() => setOpenSelectTopic(true)}262 >Change Topic</Button> : null}263 </div>264 <ListTestInfo appId={appInfoState.id}265 onChangeTestInfo={(testInfo) => {266 if (!testInfo.playing) {267 setCurrentTestInfo(testInfo);268 if (currentTestInfo) {269 setTestInfoPlaying(currentTestInfo.id, testInfo.id)270 }271 }272 setShowGame(true);273 }}274 level={gameState.level}275 bucket={appInfoState.bucket}>276 </ListTestInfo>277 </>)}278 {((Config.LISTBUCKET.indexOf(appInfoState.bucket) !== -1 && !testInfoState.currentTopic[appInfoState.id]) || openSelectTopic === true) ?279 <SelectTopicPopUp appInfoState={appInfoState}280 openSelectTopic={openSelectTopic}281 setOpenSelectTopic={() => setOpenSelectTopic(false)}>282 </SelectTopicPopUp> : null}283 {appInfoState && appInfoState.hasState ?284 <SelectStatePopup285 onLoaded={(selectedState) => {286 setSelectedState(selectedState)287 }}288 openDefault={false}289 appInfo={appInfoState}290 openPopupChangeState={openPopupChangeState}291 onHidden={() => {292 setOpenPopupChangeState(false);293 setOpenSelectTopic(true)294 }} /> : ''}295 </Container >296 <ShowImage></ShowImage>297 </div >298 )299}300const ListTestInfoUI = ({ testInfoState, appId, onChangeTestInfo, level, bucket }) => {301 let testInfos = new Array();302 const theme = useTheme();303 const isMobile = useMediaQuery(theme.breakpoints.between(0, 600))304 const isIPad = useMediaQuery(theme.breakpoints.between(600, 780))305 if (!testInfoState || testInfoState.loading) {306 return <LoadingWidget></LoadingWidget>307 }308 let widget = [], childs = [];309 if (Config.LISTBUCKET.indexOf(bucket) !== -1) {310 if (testInfoState.list.length > 0) {311 testInfoState.list.forEach(el => {312 if (el.topicId === testInfoState.currentTopic[appId]) {313 testInfos.push(el);314 }315 })316 }317 } else {318 if (testInfoState.list.length > 0) {319 testInfoState.list.forEach(el => {320 if (el.appId === appId) {321 testInfos.push(el)322 }323 })324 }325 }326 console.log("xxxxx testInfos", testInfos.length)327 testInfos.sort((a, b) => a.index - b.index).forEach((el, index) => {328 let indexInt = isMobile ? parseInt(index / 2) : (isIPad ? parseInt(index / 4) : parseInt(index / 6));329 let testInfoItem = <TestInfoItem330 onChangeTestInfo={onChangeTestInfo}331 testInfo={el}332 key={el.id}333 index={index}334 level={level}335 length={testInfos.length}336 reverse={indexInt % 2 === 0 ? false : true} >337 </TestInfoItem>338 childs.push(testInfoItem);339 if (isMobile ? (childs.length === 2 || childs.length === (testInfos.length - widget.length * 2)) : (isIPad ? (childs.length === 4 || childs.length === (testInfos.length - widget.length * 4)) : (childs.length === 6 || childs.length === (testInfos.length - widget.length * 6)))) {340 let container341 if (indexInt % 2 === 0) {342 container = <Grid container spacing={2} key={"container " + indexInt} style={{ justifyContent: (isMobile && childs.length === 2) ? "center" : "", marginBottom: isIPad ? "20px" : "12px", width: "100%", marginLeft: (isMobile && childs.length === 1) ? "calc((100% - 360px)/2)" : "auto", marginRight: "auto", marginTop: (isMobile && indexInt === 0) ? "20px" : "0px" }}>{[...childs]}</Grid>343 } else {344 container = <Grid container spacing={2} key={"container " + indexInt} style={{ justifyContent: (isMobile && childs.length === 2) ? "center" : "", margin: isIPad ? "0 auto 20px" : "0 auto 12px", flexDirection: "row-reverse", width: "100%", marginLeft: (isMobile && childs.length === 1) ? "calc((360px - 100%)/2)" : "auto" }}>{[...childs]}</Grid>345 }346 widget.push(container);347 childs = []348 }349 })350 console.log("xxx widget", widget)351 return (352 <>353 { widget}354 </>355 )356}357const TestInfoItem = ({ testInfo, onChangeTestInfo, index, level, reverse, length }) => {358 let status = testInfo.statusProgress359 const theme = useTheme();360 const [showAlert, setShowAlert] = useState();361 const isMobile = useMediaQuery(theme.breakpoints.between(0, 600));362 const isIPad = useMediaQuery(theme.breakpoints.between(600, 780));363 return (364 <Grid item xs={isMobile ? 6 : (isIPad ? 3 : 2)} style={{ maxWidth: isMobile ? "180px" : (isIPad ? "" : "") }} onClick={() => {365 if (testInfo.lock) {366 setShowAlert(true)367 } else {368 onChangeTestInfo(testInfo)369 }370 }} className="test-info-item" >371 <div className="test-info-item-container" style={(isMobile && index % 2 === 0 || isIPad && index % 4 !== 3 || !isMobile && !isIPad && index % 6 !== 5) ? { display: "block" } : { display: "flex", width: (isMobile || isIPad) ? "154px" : "" }}>372 {showAlert ? <CongratulationAlert page="test" onClose={() => setShowAlert(false)}></CongratulationAlert> : null}373 {((!isMobile && !isIPad && index % 6 !== 5) || (isMobile && index % 2 === 0) || (isIPad && index % 4 !== 3) ? (374 <>375 <div className="test-info-item-top" style={{ border: index === 0 ? "2px solid #4e63bd" : "2px dashed #4e63bd" }}></div>376 <div className="test-info-item-bottom" style={{ border: index === 0 ? "2px dashed #4e63bd" : "2px solid #4e63bd" }}></div>377 </>378 ) : (379 <>380 <div className="test-info-item-left" style={{ border: reverse ? "2px dashed #4e63bd" : "2px solid #4e63bd" }}></div>381 <div className="test-info-item-right" style={{ border: reverse ? "2px solid #4e63bd" : "2px dashed #4e63bd" }}></div>382 </>383 ))}384 <div className="test-info-item-content">385 <div className="circle-progress">386 {testInfo.lock ? null : <div className="circle-progress-content" style={status === Config.GAME_STATUS_FAILED ? { background: "#FE6D6D", boxShadow: "none" } : { background: "linear-gradient(108.3deg, #3a95dc 23.49%, #96d9ff 76.7%)" }}>{status === Config.TEST_STATUS_NOTHING ? <PlayArrow style={{ margin: "auto" }}></PlayArrow> : (387 status === Config.GAME_STATUS_PASSED ? <Done></Done> : (status === Config.GAME_STATUS_FAILED ? <CloseIcon style={{ color: "#fff" }}></CloseIcon> : (level === -1 ? testInfo.progress + "%" : testInfo.calculateProgress(level) + "%"))388 )}</div>}389 {testInfo.lock ? <LockIcon style={{ color: "#DADADA", margin: "auto" }}></LockIcon> : null}390 </div>391 <div className="test-info-title">{testInfo.title + " " + (index + 1).toString()}</div>392 </div>393 {index === length - 1 ? null : <ArrowRightAltIcon style={394 isMobile ? (index % 2 === 0 ?395 {396 color: "#4E63BD",397 position: "absolute",398 top: "42%",399 right: reverse ? "" : "-37px",400 left: reverse ? "-33px" : "",401 fontSize: "40px",402 transform: reverse ? "rotate(180deg)" : ""403 } :404 {405 color: "#4E63BD",406 position: "absolute",407 top: "97%",408 left: "38%",409 fontSize: "40px",410 transform: "rotate(90deg)"411 }) : (isIPad ?412 (413 index % 4 === 3 ?414 {415 color: "#4E63BD",416 position: "absolute",417 top: "96%",418 left: "37%",419 fontSize: "51px",420 transform: "rotate(90deg)"421 } :422 {423 color: "#4E63BD",424 position: "absolute",425 top: "37%",426 right: (reverse ? "" : "-51px"),427 left: (reverse ? "-48px" : ""),428 fontSize: "57px",429 transform: (reverse ? "rotate(180deg)" : "")430 }431 ) :432 (433 (index % 6 === 5 ?434 {435 color: "#4E63BD",436 position: "absolute",437 top: "100%",438 right: "",439 left: "42%",440 fontSize: "34px",441 transform: "rotate(90deg)"442 } :443 {444 color: "#4E63BD",445 position: "absolute",446 top: "42%",447 right: (reverse ? "" : "-31px"),448 left: (reverse ? "-28px" : ""),449 fontSize: "34px",450 transform: (reverse ? "rotate(180deg)" : "")451 })452 ))453 }></ArrowRightAltIcon>}454 </div>455 </Grid >456 )457}458const ListTestInfo = connect((state, ownProps) => {459 return {460 testInfoState: state.testInfoReducer,461 ...ownProps462 }463}, null)(ListTestInfoUI)464const mapStateToProps = (state, ownProps) => {465 return {466 testInfoState: state.testInfoReducer,467 gameState: state.gameState,468 stateInfoState: state.stateInfoState,469 ...ownProps470 };471}472const mapDispatchToProps = (dispatch) => ({473 getTestInfoByAppId: (appId, stateId) => dispatch(getTestInfoByAppId(appId, stateId)),474 endTest: () => dispatch(endTest()),475 getTopicsByParentId: (appId) => dispatch(getTopicsByParentId(appId)),476 setTestInfoPlaying: (prevId, nextId) => dispatch(setTestInfoPlaying(prevId, nextId)),477 getTestInfoByAppIdAndParentId: (appId) => dispatch(getTestInfoByAppIdAndParentId(appId))478});479const TestView = connect(mapStateToProps, mapDispatchToProps)(TestViewUI)...

Full Screen

Full Screen

original-harness.js

Source:original-harness.js Github

copy

Full Screen

1var ReflectionHarness = {};2// @private3ReflectionHarness.passed = document.getElementById("passed");4ReflectionHarness.failed = document.getElementById("failed");5/**6 * In conformance testing mode, all tests will be run. Otherwise, we'll skip7 * tests for attributes that have an entirely incorrect type.8 */9ReflectionHarness.conformanceTesting = false;10/**11 * Returns a string representing val. Basically just adds quotes for strings,12 * and passes through other recognized types literally.13 *14 * @public15 */16ReflectionHarness.stringRep = function(val) {17 if (val === null) {18 // typeof is object, so the switch isn't useful19 return "null";20 }21 // In JavaScript, -0 === 0 and String(-0) == "0", so we have to22 // special-case.23 if (val === -0 && 1/val === -Infinity) {24 return "-0";25 }26 switch (typeof val) {27 case "string":28 for (var i = 0; i < 32; i++) {29 var replace = "\\";30 switch (i) {31 case 0: replace += "0"; break;32 case 1: replace += "x01"; break;33 case 2: replace += "x02"; break;34 case 3: replace += "x03"; break;35 case 4: replace += "x04"; break;36 case 5: replace += "x05"; break;37 case 6: replace += "x06"; break;38 case 7: replace += "x07"; break;39 case 8: replace += "b"; break;40 case 9: replace += "t"; break;41 case 10: replace += "n"; break;42 case 11: replace += "v"; break;43 case 12: replace += "f"; break;44 case 13: replace += "r"; break;45 case 14: replace += "x0e"; break;46 case 15: replace += "x0f"; break;47 case 16: replace += "x10"; break;48 case 17: replace += "x11"; break;49 case 18: replace += "x12"; break;50 case 19: replace += "x13"; break;51 case 20: replace += "x14"; break;52 case 21: replace += "x15"; break;53 case 22: replace += "x16"; break;54 case 23: replace += "x17"; break;55 case 24: replace += "x18"; break;56 case 25: replace += "x19"; break;57 case 26: replace += "x1a"; break;58 case 27: replace += "x1b"; break;59 case 28: replace += "x1c"; break;60 case 29: replace += "x1d"; break;61 case 30: replace += "x1e"; break;62 case 31: replace += "x1f"; break;63 }64 val = val.replace(String.fromCharCode(i), replace);65 }66 return '"' + val.replace('"', '\\"') + '"';67 case "boolean":68 case "undefined":69 case "number":70 return val + "";71 default:72 return typeof val + ' "' + val + '"';73 }74}75/**76 * An object representing info about the current test, used for printing out77 * nice messages and so forth.78 */79ReflectionHarness.currentTestInfo = {};80/**81 * .test() sets this, and it's used by .assertEquals()/.assertThrows().82 * Calling .test() recursively is an error.83 */84ReflectionHarness.currentTestDescription = null;85/**86 * Run a group of one or more assertions. If any exceptions are thrown, catch87 * them and report a failure.88 */89ReflectionHarness.test = function(fn, description) {90 if (this.currentTestDescription) {91 throw "TEST BUG: test() may not be called recursively!";92 }93 this.currentTestDescription = description;94 try {95 fn();96 // Not throwing is a success97 this.success();98 } catch(err) {99 this.failure("Exception thrown during tests with " + description);100 }101 this.currentTestDescription = null;102}103/**104 * If question === answer, output a success, else report a failure with the105 * given description. Currently success and failure both increment counters,106 * and failures output a message to a <ul>. Which <ul> is decided by the type107 * parameter -- different attribute types are separated for readability.108 *109 * @public110 */111ReflectionHarness.assertEquals = function(expected, actual, description) {112 // Special-case -0 yay!113 if (expected === 0 && actual === 0 && 1/expected === 1/actual) {114 this.increment(this.passed);115 } else if (expected === actual) {116 this.increment(this.passed);117 } else {118 this.increment(this.failed);119 this.reportFailure(this.currentTestDescription +120 (description ? " followed by " + description : "") +121 ' (expected ' + this.stringRep(actual) + ', got ' +122 this.stringRep(expected) + ')');123 }124}125/**126 * If calling fn causes a DOMException of the type given by the string127 * exceptionName (e.g., "IndexSizeError"), output a success. Otherwise, report128 * a failure.129 *130 * @public131 */132ReflectionHarness.assertThrows = function(exceptionName, fn) {133 try {134 fn();135 } catch (e) {136 if (e instanceof DOMException && e.code == DOMException[exceptionName]) {137 this.increment(this.passed);138 return true;139 }140 }141 this.increment(this.failed);142 this.reportFailure(this.currentTestDescription + " must throw " +143 exceptionName);144 return false;145}146/**147 * Get a description of the current type, e.g., "a.href".148 */149ReflectionHarness.getTypeDescription = function() {150 var domNode = this.currentTestInfo.domObj.tagName.toLowerCase();151 var idlNode = this.currentTestInfo.idlObj.nodeName.toLowerCase();152 var domName = this.currentTestInfo.domName;153 var idlName = this.currentTestInfo.idlName;154 var comment = this.currentTestInfo.data.comment;155 var typeDesc = idlNode + "." + idlName;156 if (!comment && (domNode != idlNode || domName != idlName)) {157 comment = "<" + domNode + " " + domName + ">";158 }159 if (comment) {160 typeDesc += " (" + comment + ")";161 }162 return typeDesc;163}164/**165 * Report a failure with the given description, adding context from the166 * currentTestInfo member.167 *168 * @private169 */170ReflectionHarness.reportFailure = function(description) {171 var typeDesc = this.getTypeDescription();172 var idlName = this.currentTestInfo.idlName;173 var comment = this.currentTestInfo.data.comment;174 typeDesc = typeDesc.replace("&", "&amp;").replace("<", "&lt;");175 description = description.replace("&", "&amp;").replace("<", "&lt;");176 var type = this.currentTestInfo.data.type;177 // Special case for undefined attributes, which we don't want getting in178 // the way of everything else.179 if (description.search('^typeof IDL attribute \\(expected ".*", got "undefined"\\)$') != -1) {180 type = "undefined";181 }182 var done = false;183 var ul = document.getElementById("errors-" + type.replace(" ", "-"));184 if (ul === null) {185 ul = document.createElement("ul");186 ul.id = "errors-" + type.replace(" ", "-");187 var div = document.getElementById("errors");188 p = document.createElement("p");189 if (type == "undefined") {190 div.parentNode.insertBefore(ul, div.nextSibling);191 p.innerHTML = "These IDL attributes were of undefined type, presumably representing unimplemented features (cordoned off into a separate section for tidiness):";192 } else {193 div.appendChild(ul);194 p.innerHTML = "Errors for type " + type + ":";195 }196 ul.parentNode.insertBefore(p, ul);197 } else if (type != "undefined") {198 var existingErrors = ul.getElementsByClassName("desc");199 for (var i = 0; i < existingErrors.length; i++) {200 if (existingErrors[i].innerHTML == description) {201 var typeSpan = existingErrors[i].parentNode.getElementsByClassName("type")[0];202 // Check if we have lots of the same error for the same203 // attribute. If so, we want to collapse them -- the exact204 // elements that exhibit the error aren't going to be important205 // to report in this case, and it can take a lot of space if206 // there's an error in a global attribute like dir or id.207 var types = typeSpan.innerHTML.split(", ");208 var count = 0;209 for (var i = 0; i < types.length; i++) {210 if (types[i].search("^\\([0-9]* elements\\)\\." + idlName + "$") != -1) {211 types[i] = "(" + (1 + parseInt(/[0-9]+/.exec(types[i])[0])) + " elements)." + idlName;212 typeSpan.innerHTML = types.join(", ");213 return;214 } else if (types[i].search("\\." + idlName + "$") != -1) {215 count++;216 }217 }218 if (comment || count < 10) {219 // Just add the extra error to the end, not many duplicates220 // (or we have a comment)221 typeSpan.innerHTML += ", " + typeDesc;222 } else {223 var filteredTypes = types.filter(function(type) { return type.search("\\." + idlName + "$") == -1; });224 if (filteredTypes.length) {225 typeSpan.innerHTML = filteredTypes.join(", ") + ", ";226 } else {227 typeSpan.innerHTML = "";228 }229 typeSpan.innerHTML += "(" + (types.length - filteredTypes.length) + " elements)." + idlName;230 }231 return;232 }233 }234 }235 if (type == "undefined") {236 ul.innerHTML += "<li>" + typeDesc;237 } else {238 ul.innerHTML += "<li><span class=\"type\">" + typeDesc + "</span>: <span class=\"desc\">" + description + "</span>";239 }240}241/**242 * Shorthand function for when we have a failure outside of243 * assertEquals()/assertThrows(). Generally used when the failure is an244 * exception thrown unexpectedly or such, something not equality-based.245 *246 * @public247 */248ReflectionHarness.failure = function(message) {249 this.increment(this.failed);250 this.reportFailure(message);251}252/**253 * Shorthand function for when we have a success outside of254 * assertEquals()/assertThrows().255 *256 * @public257 */258ReflectionHarness.success = function() {259 this.increment(this.passed);260}261/**262 * Increment the count in either "passed" or "failed". el should always be one263 * of those two variables. The implementation of this function amuses me.264 *265 * @private266 */267ReflectionHarness.increment = function(el) {268 el.innerHTML = parseInt(el.innerHTML) + 1;269 var percent = document.getElementById("percent");270 var passed = document.getElementById("passed");271 var failed = document.getElementById("failed");272 percent.innerHTML = (parseInt(passed.innerHTML)/(parseInt(passed.innerHTML) + parseInt(failed.innerHTML))*100).toPrecision(3);273}274/**275 * Hide all displayed errors matching a given regex, so it's easier to filter276 * out repetitive failures. TODO: Fix this so it works right with the new277 * "lump many errors in one <li>" thing.278 *279 * @private (kind of, only called in the original reflection.html)280 */281ReflectionHarness.maskErrors = function(regex) {282 var uls = document.getElementsByTagName("ul");283 for (var i = 0; i < uls.length; i++) {284 var lis = uls[i].children;285 for (var j = 0; j < lis.length; j++) {286 if (regex !== "" && lis[j].innerHTML.match(regex)) {287 lis[j].style.display = "none";288 } else {289 lis[j].style.display = "list-item";290 }291 }292 }293}294// Now for some stuff that has nothing to do with ReflectionHarness and295// everything to do with initialization needed for reflection.js, which seems296// pointless to put in an extra file.297var elements = {};298var extraTests = [];299/**300 * Used for combining a number of small arrays of element data into one big301 * one.302 */303function mergeElements(src) {304 for (var key in src) {305 if (!src.hasOwnProperty(key)) {306 // This is inherited from a prototype or something.307 continue;308 }309 if (key in elements) {310 elements[key] = elements[key].concat(src[key]);311 } else {312 elements[key] = src[key];313 }314 }...

Full Screen

Full Screen

MinimaxContext.js

Source:MinimaxContext.js Github

copy

Full Screen

1// libraries and hooks2import { createContext, useContext } from "react";3// algorithm4import { GameContext } from "@context/GameContext";56export const MinimaxContext = createContext();78export const MinimaxContextProvider = ({ children }) => {9 const AIMark = "O";10 const humanMark = "X";1112 const { findEmptyCells, checkWinner } = useContext(GameContext);1314 const findBestMove = (board, playerMark) => {15 // the algorithm gets the indexes of all the empty cells.16 const availableCells = findEmptyCells(board);1718 // the algorithm checks whether someone has already won.19 if (checkWinner(board, humanMark)) {20 // if the human wins, then return -121 return { score: -1 };22 } else if (checkWinner(board, AIMark)) {23 // if the AI wins, then return 124 return { score: 1 };25 } else if (availableCells.length === 0) {26 // finally, if there are no more available cells, it means the game has ended in a tie, therefore return 0.27 return { score: 0 };28 }2930 // this array will save the information of all the tests.31 const allTestsInformation = [];3233 for (let i = 0; i < availableCells.length; i++) {34 // now we will iterate upon all the available cells.35 const currentTestInfo = {}; //this variable saves the info of the current test.36 currentTestInfo.index = board[availableCells[i].index].index;37 // then we will place the player mark in the current available cell.38 board[availableCells[i].index].isMarked = true;39 board[availableCells[i].index].markedBy = playerMark;40 //is the AI the current player?41 if (playerMark === AIMark) {42 //if so, recursively run the algorithm with the new board state and with the humanMark (the next player) and save its result in the result variable.43 const result = findBestMove(board, humanMark);44 // and add this result info to the currentTestInfo object.45 currentTestInfo.score = result.score;46 } else {47 //else, recursively run the algorithm with the new board state and with the AImark (the next player) and save its result in the result variable.48 const result = findBestMove(board, AIMark);49 // and add this result info to the currentTestInfo object.50 currentTestInfo.score = result.score;51 }52 // now delete the player mark from the current cell.53 board[availableCells[i].index].isMarked = false;54 board[availableCells[i].index].markedBy = null;55 // and push the currentTestInfo to the array with all the tests.56 allTestsInformation.push(currentTestInfo);57 }5859 // this is the variable that we will return later on.60 let bestPlay = null;6162 // is the AI (the maximizer) the current player?63 if (playerMark === AIMark) {64 // if so, then:65 let bestScore = -9999999; //the best score is initialized with a negative number.66 for (let i = 0; i < allTestsInformation.length; i++) {67 //we'll iterate upon the array with all the tests.68 if (allTestsInformation[i].score > bestScore) {69 // if the score of the test at i position is greater than bestScore, then:70 // bestScore will change its value to the score of the test at position i.71 bestScore = allTestsInformation[i].score;72 // and the best play for the maximizer will be equal to the test at i position.73 bestPlay = i;74 }75 }76 } else {77 // else, it means the current player is the human (the minimizer)78 let bestScore = 9999999; // for the minimizer, we'll start its best value as a positive number.79 for (let i = 0; i < allTestsInformation.length; i++) {80 //we'll iterate upon the array with all the tests.81 if (allTestsInformation[i].score < bestScore) {82 // if the score of the test at i position is lesser than bestScore, then:83 // bestScore will change its value to the score of the test at position i.84 bestScore = allTestsInformation[i].score;85 // and the best play for the minimizer will be equal to the test at i position.86 bestPlay = i;87 }88 }89 }90 // finally, return the best play found in the tests array.91 return allTestsInformation[bestPlay];92 };9394 return (95 <MinimaxContext.Provider value={{ findBestMove }}>96 {children}97 </MinimaxContext.Provider>98 ); ...

Full Screen

Full Screen

ResultsView.jsx

Source:ResultsView.jsx Github

copy

Full Screen

1import { useCallback } from 'react';2import { Link } from 'react-router-dom';3import { useLocation } from 'react-router';4import { useEffect } from 'react';5import { useSelector, useDispatch } from 'react-redux';6import PropTypes from 'prop-types';7import Container from '../../components/Container';8import TestResult from '../../components/TestResult';9import { testScoreOperations } from '../../redux/testScore';10import { getTestInfo } from '../../redux/testScore/test-selectors.js';11import { currentTestInfoSlice } from '../../redux/testScore/test-reducers.js';12import s from './ResultsView.module.css';13import { authActions } from 'redux/auth';14const ResultsView = () => {15 const currentTestInfo = useSelector(getTestInfo);16 const dispatch = useDispatch();17 const location = useLocation();18 useEffect(() => {19 dispatch(authActions.setUserLocation(location.pathname));20 // eslint-disable-next-line21 }, []);22 const handleRetryBtnClick = useCallback(23 (url, info) => {24 dispatch(testScoreOperations.getQuestions(url));25 dispatch(currentTestInfoSlice.actions.setInfo(info));26 },27 [dispatch],28 );29 return (30 <Container>31 <div className={s.content}>32 <h1 className={s.mainTitle}>Results</h1>33 <h2 className={s.mainSubtitle}>[ {currentTestInfo.quizName}_]</h2>34 <TestResult />35 <Link36 to={{37 pathname: '/test',38 state: {39 quizName: currentTestInfo.quizName,40 url: currentTestInfo.url,41 },42 }}43 className={s.btnRetry}44 onClick={() =>45 handleRetryBtnClick(currentTestInfo.url, {46 quizName: currentTestInfo.quizName,47 url: currentTestInfo.url,48 })49 }50 >51 Try again52 </Link>53 </div>54 </Container>55 );56};57ResultsView.propTypes = {58 currentTestInfo: PropTypes.objectOf(59 PropTypes.exact({60 quizName: PropTypes.string.isRequired,61 url: PropTypes.string.isRequired,62 }),63 ),64};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { test } = require('@playwright/test');2test.describe('test', () => {3 test('test', async ({ page }) => {4 const title = page.currentTestInfo().title;5 console.log(title);6 });7});8const { test, expect } = require('@playwright/test');9test.use({10 reporter: new (require('@playwright/test/lib/reporters/list'))(),11});12test('test', async ({ page }) => {13 const title = page.currentTestInfo().title;14 console.log(title);15});16const { test, expect } = require('@playwright/test');17test.use({18 runner: new (require('@playwright/test/lib/runner'))(),19});20test('test', async ({ page }) => {21 const title = page.currentTestInfo().title;22 console.log(title);23});24const { test, expect } = require('@playwright/test');25test.use({26 runner: new (require('@playwright/test/lib/runner'))(),27 reporter: new (require('@playwright/test/lib/reporters/list'))(),28});29test('test', async ({ page }) => {30 const title = page.currentTestInfo().title;31 console.log(title

Full Screen

Using AI Code Generation

copy

Full Screen

1const { currentTestInfo } = require('@playwright/test');2const test = currentTestInfo();3const title = test.title;4console.log(title);5const { test, expect } = require('@playwright/test');6test('My test', async ({ page }) => {7 expect(page.title()).toBe('Playwright');8});9const context = await browser.newContext();10const context = await browser.newContext({11 userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36',12 viewport: { width: 1280, height: 720 }13});14| `deviceScaleFactor` | `number` | `1` | Specify device scale factor (can be thought of as dpr). |15| `geolocation` | `{ latitude: number, longitude: number, accuracy?: number }` | `null` | A geolocation to use. |

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful