Best JavaScript code snippet using testcafe
assertion-helper.js
Source:assertion-helper.js  
...47        .then(function (png) {48            const width  = png.width;49            const height = png.height;50            // NOTE: sometimes an appearing dialog can cover an edge of the browser. Try to check all edges51            return hasPixel(png, RED_PIXEL, 0, 0) && hasPixel(png, RED_PIXEL, 49, 49) && hasPixel(png, GREEN_PIXEL, 50, 50) ||52                   hasPixel(png, RED_PIXEL, width - 1, height - 1) && hasPixel(png, RED_PIXEL, width - 50, height - 50) && hasPixel(png, GREEN_PIXEL, width - 51, height - 51) ||53                   hasPixel(png, RED_PIXEL, width - 1, 0) && hasPixel(png, RED_PIXEL, width - 50, 49) && hasPixel(png, GREEN_PIXEL, width - 51, 50) ||54                   hasPixel(png, RED_PIXEL, 0, height - 1) && hasPixel(png, RED_PIXEL, 49, height - 50) && hasPixel(png, GREEN_PIXEL, 50, height - 51);55        });56}57function checkScreenshotFileFullPage (filePath) {58    return readPngFile(filePath)59        .then(function (png) {60            const width  = png.width;61            const height = png.height;62            const expectedHeight = 5000;63            return height === expectedHeight &&64                hasPixel(png, RED_PIXEL, 0, 0) &&65                hasPixel(png, RED_PIXEL, width - 1, height - 1) &&66                hasPixel(png, GREEN_PIXEL, 0, height - 1) &&67                hasPixel(png, GREEN_PIXEL, width - 1, 0);68        });69}70function checkScreenshotFileIsNotWhite (filePath) {71    return readPngFile(filePath)72        .then(function (png) {73            return png.data.indexOf(Buffer.from(RED_PIXEL)) > -1 && png.data.indexOf(Buffer.from(GREEN_PIXEL)) > -1;74        });75}76function isDirExists (folderPath) {77    let exists = false;78    try {79        exists = fs.statSync(folderPath).isDirectory();80    }81    catch (e) {...glUtil.js
Source:glUtil.js  
...67    return !!data[(j * ctx.canvas.width + i) * 4 + 3];68  };69  var markPoint = function (j, i) {70    var value = 0;71    if (i > 0 && hasPixel(j, i - 1)) {72      //ä¸å·¦è¾¹è¿é73      value = g[j][i - 1];74    } else {75      value = ++cnt;76    }77    if ( j > 0 && hasPixel(j - 1, i) && ( i === 0 || !hasPixel(j - 1, i - 1) ) ) {78      //ä¸ä¸è¿é ä¸ ä¸å·¦ä¸ä¸è¿é ï¼å³é¦æ¬¡åä¸ä¸è¡è¿æ¥ï¼79      if (g[j - 1][i] !== value) {80        markMap.push([g[j - 1][i], value]);81      }82    }83    if ( !hasPixel(j, i - 1) ) {84      //è¡é¦85      if ( hasPixel(j - 1, i - 1) && g[j - 1][i - 1] !== value) {86        //ä¸å·¦ä¸è¿é87        markMap.push([g[j - 1][i - 1], value]);88      }89    }90    if ( !hasPixel(j, i + 1) ) {91      //è¡å°¾92      if ( hasPixel(j - 1, i + 1) && g[j - 1][i + 1] !== value) {93        //ä¸å³ä¸è¿é94        markMap.push([g[j - 1][i + 1], value]);95      }96    }97    return value;98  };99  for (var j = 0; j < ctx.canvas.height; j += grid) {100    g.push([]);101    e.push([]);102    for (var i = 0; i < ctx.canvas.width; i += grid) {103      var value = 0;104      var isEdge = false;105      if (hasPixel(j, i)) {106        value = markPoint(j, i);107      }108      e[j][i] = isEdge;109      g[j][i] = value;110    }111  }112  var finalGraph = seperateGraph(g, e, markMap, cnt);113  var graphs = finalGraph[0];114  var sampledEdge = finalGraph[2];115  var graphMap = [];116  var z = options.thick / 2;117  var z2 = -z;118  sampledEdge.forEach(function (graph, index) {119    var points = graph[0];...cluster.js
Source:cluster.js  
...68    //Center69    if(!this._app.test_pixel(start_pixel)){70        return false;71    }72    if(!this.hasPixel(start_pixel)){73        this.addPixel(start_pixel);74    }75    var row_start = (start_pixel.row - this._app.options.tollerence);76    var row_end = (start_pixel.row + this._app.options.tollerence);77    //console.log("row: " + row_start + '  ----  ' + row_end);78    var results = {79        top:{80            left:{81                avg:0,82                count:083            },84            center:{85                avg:0,86                count:087            },88            right:{89                avg:0,90                count:091            }92        },93        middle:{94            left:{95                avg:0,96                count:097            },98            center:{99                avg:0,100                count:0101            },102            right:{103                avg:0,104                count:0105            }106        },107        bottom:{108            left:{109                avg:0,110                count:0111            },112            center:{113                avg:0,114                count:0115            },116            right:{117                avg:0,118                count:0119            }120        }121    }122    for(var row = row_start; row < row_end; row ++){123        var col_start = (start_pixel.col - (this._app.options.tollerence - (start_pixel.row - row)));124        var col_end = (start_pixel.col + (this._app.options.tollerence - (start_pixel.row - row)));125        //console.log("col: " + col_start + '    -----  ' + col_end);126        for(var col = col_start; col < col_end; col ++){127            //console.log(row + ', ' + col);128            var comp = (grid[row] && grid[row][col]) || null;129            if(130                comp &&131                !comp.cluster &&132                !this.hasPixel(comp)133            ){134                var result_set = null;135                if(row < start_pixel.row){136                    result_set = results.top;137                }else if(row > start_pixel.row){138                    result_set = results.bottom;139                }else{140                    result_set = results.middle;141                }142                if(col < start_pixel.col){143                    result_set = result_set.left;144                }else if(col > start_pixel.col){145                    result_set = result_set.right;146                }else{147                    result_set = result_set.center;148                }149                result_set.count += 1;150                if(this._app.test_pixel(comp)){151                    result_set.avg += 1;152                }153            }154        }155    }156    for(var row_key in results){157        for(var col_key in results[row_key]){158            var result_set = results[row_key][col_key];159            if(result_set.count/result_set.avg > .5){160                var row = start_pixel.row;161                var col = start_pixel.col;162                if(row_key == 'top'){163                    row -= 1;164                }else if(row_key == 'bottom'){165                    row += 1;166                }167                if(col_key == 'left'){168                    col -= 1;169                }else if(col_key == 'right'){170                    col += 1;171                }172                var comp = (grid[row] && grid[row][col]) || null;173                if(174                    comp &&175                    !comp.cluster &&176                    !this.hasPixel(comp)177                ){178                    //process.nextTick(_.bind(function(){179                        this.expand(comp, callback);180                    //}, this));181                }182            }183        }184    }185    //throw Error("Bangski");186}187/*Cluster.prototype.expand = function(start_pixel){188    var grid = this.grid;189    console.log("Expanding: " + start_pixel.row + ',' + start_pixel.col);190    //Got to test 9 touching pixels191    //Center192    if(!this._app.test_pixel(start_pixel)){193        return false;194    }195    if(!this.hasPixel(start_pixel)){196        this.addPixel(start_pixel);197    }198    //TOP Left199    var top_left = (grid[start_pixel.row - 1] && grid[start_pixel.row - 1][start_pixel.col - 1]) || null;200    if(201        top_left &&202            !this.hasPixel(top_left) &&203            this._app.test_pixel(top_left)204        ){205        this.expand(top_left);206    }207    //TOP Center208    var top_center = (grid[start_pixel.row - 1] && grid[start_pixel.row - 1][start_pixel.col]) || null;209    if(210        top_center &&211            !this.hasPixel(top_center) &&212            this._app.test_pixel(top_center)213        ){214        this.expand(top_center);215    }216    //TOP right217    var top_right = (grid[start_pixel.row - 1] && grid[start_pixel.row - 1][start_pixel.col + 1]) || null;218    if(219        top_right &&220            !this.hasPixel(top_right) &&221            this._app.test_pixel(top_right)222        ){223        this.expand(top_right);224    }225    //Middle Left226    var middle_left = (grid[start_pixel.row] && grid[start_pixel.row][start_pixel.col - 1]) || null;227    if(228        middle_left &&229            !this.hasPixel(middle_left) &&230            this._app.test_pixel(middle_left)231        ){232        this.expand(middle_left);233    }234    //Middle Right235    var middle_right = (grid[start_pixel.row] && grid[start_pixel.row][start_pixel.col + 1]) || null;236    if(237        middle_right &&238            !this.hasPixel(middle_right) &&239            this._app.test_pixel(middle_right)240        ){241        this.expand(middle_right);242    }243    //Bottom Left244    var bottom_left = (grid[start_pixel.row + 1] && grid[start_pixel.row + 1][start_pixel.col - 1]) || null;245    if(246        bottom_left &&247            !this.hasPixel(bottom_left) &&248            this._app.test_pixel(bottom_left)249        ){250        this.expand(bottom_left);251    }252    //Bottom Center253    var bottom_center = (grid[start_pixel.row + 1] && grid[start_pixel.row + 1][start_pixel.col]) || null;254    if(255        bottom_center &&256            !this.hasPixel(bottom_center) &&257            this._app.test_pixel(bottom_center)258        ){259        this.expand(bottom_center);260    }261    //Bottom right262    var bottom_right = (grid[start_pixel.row + 1] && grid[start_pixel.row + 1][start_pixel.col + 1]) || null;263    if(264        bottom_right &&265            !this.hasPixel(bottom_right) &&266            this._app.test_pixel(bottom_right)267        ){268        this.expand(bottom_right);269    }270}*/271Cluster.prototype.hasPixel = function(pixel){272    return (this.pixels[pixel.row] && this.pixels[pixel.row][pixel.col]);273}274Cluster.prototype.drawToCanvas = function(canvas, ctx){275    //DEBUG STUFF:276    var r = 128 + Math.floor(Math.random() * 128);277    var g = 128 + Math.floor(Math.random() * 128);278    var b = 128 + Math.floor(Math.random() * 128);279    var img_data = ctx.getImageData(...App.js
Source:App.js  
1import { useEffect, useState } from "react";2import { makeStyles } from '@material-ui/core/styles';3import { Container, Typography, AppBar, IconButton, Button, Select, MenuItem, Tooltip, Input} from "@material-ui/core";4import BugReportIcon from '@material-ui/icons/BugReport';5import EditIcon from '@material-ui/icons/Edit';6import { csvToMatrix, findIndexMax, predict } from "./lib/ml";7import { CustomMenuContext } from "./components/CustomMenu";8import Drawing from "./components/Drawing";9const useStyles = makeStyles(theme => ({10  predictions: {11    display: 'flex',12    flexDirection: 'column'13  },14  prediction: {15    padding: '0.3em 0'16  },17  confident: {18    color: 'green',19    fontWeight: 'bold'20  },21  title: {22    flexGrow: 1,23    margin: theme.spacing(2),24  },25  app: {26    paddingTop: theme.spacing(1),27    display: 'flex',28    flexWrap: 'nowrap',29    justifyContent: 'space-between',30  },31  btns: {32    '& > *': {33      margin: theme.spacing(0.25),34    },35  }36}));37function App() {38  const classes = useStyles();39  const [theta1, setTheta1] = useState(null);40  const [theta2, setTheta2] = useState(null);41  const [pixels, setPixels] = useState([]);42  const [predictions, setPredictions] = useState([]);43  const [maxPrediction, setMaxPrediction] = useState(null);44  const [debug, setDebug] = useState(false);45  const [model, setModel] = useState('backprop');46  const [key, setKey] = useState(new Date().toISOString());47  const [data, setData] = useState([]);48  const [label, setLabel] = useState(10);49  const [editting, setEditting] = useState(false);50  const [hasPixel, setHasPixel] = useState(false);51  useEffect(() => {52    fetch(`/weights/${model}-weights-1.csv`, { dataType: 'text' })53    .then(r => r.text())54    .then(csvToMatrix)55    .then(setTheta1);56    fetch(`/weights/${model}-weights-2.csv`, { dataType: 'text' })57    .then(r => r.text())58    .then(csvToMatrix)59    .then(setTheta2)60  }, [model])61  useEffect(() => {62    if (editting) {63      for (let i = 0; i < pixels.length; i++) {64        if (pixels[i] !== 0) {65          setHasPixel(true);66          return;67        }68      }69    }70  }, [editting, pixels, setHasPixel]);71  const clearCanvas = () => {72    setKey(new Date().toISOString());73    setPixels([]);74    setHasPixel(false);75    setPredictions([]);76  }77  const getPrediction = () => {78    if (pixels.length) {79      const [predictions] = predict(pixels, [theta1, theta2]).toArray();80      setPredictions(predictions);81      setMaxPrediction(findIndexMax(predictions));82    }83  }84  const selectModel = e => {85    setModel(e.target.value);86  }87  const toggleDebug = () => {88    setDebug(debug => !debug);89  }90  const toggleEdit = () => {91    setEditting(editting => !editting);92  }93  const changeLabel = (e) => {94    setLabel(e.target.value);95  }96  const addData = () => {97    const newData = [...data];98    newData.push([...pixels, label]);99    setData(newData);100    clearCanvas();101  }102  const exportData = async () => {103    const csv = data.map(row => row.join(",")).join("\n");104    const fileHandle = await window.showSaveFilePicker();105    const stream = fileHandle.createWritable();106    await stream.write(csv);107    await stream.close();108  }109  return (110    <CustomMenuContext.Provider value={{ hidden: !debug, toggleMenu: toggleDebug }}>111      <AppBar position="static">112        <Typography variant="h6" className={classes.title}>113          Draw a number114        </Typography>115      </AppBar>116      <Container maxWidth="sm" className={classes.app}>117        <div>118          <Drawing119            key={key}120            onChange={setPixels}121            debug={debug}122          />123          <div className={classes.btns}>124            <Select labelId="model" id="model" onChange={selectModel} value={model}>125              <MenuItem value="backprop">Backpropagation</MenuItem>126            </Select>127            <Button onClick={getPrediction} disabled={hasPixel} variant="contained" color="primary">Check</Button>128            <Button onClick={clearCanvas} variant="contained" color="secondary">Clear</Button>129            <Tooltip title={debug? 'On': 'Off'}>130            <IconButton aria-label="debug" color={debug ? "primary" : "default" } onClick={toggleDebug}>131              <BugReportIcon />132            </IconButton>133            </Tooltip>134            <IconButton aria-label="edit" color={editting ? "primary" : "default"} onClick={toggleEdit}>135              <EditIcon />136            </IconButton>137          </div>138          {139            editting && <>140              <Input value={label} type="number" min={1} max={10} onChange={changeLabel} />141              <Button onClick={addData} disabled={!hasPixel} color="secondary">Add</Button>142              <Button onClick={exportData} color="primary">Export ({data.length})</Button>143            </>144          }145        </div>146        <div>147          <Typography variant="h6">148            Guesses149          </Typography>150        {predictions.length > 0 && (151            <div className={`${classes.predictions} ${predictions[maxPrediction] >= 0.5 ? classes.confident : ''}`}>152              {(maxPrediction + 1) % 10} : {(predictions[maxPrediction] * 100).toFixed(2)}%153            </div>154        )}155        </div>156        </Container>157    </CustomMenuContext.Provider>158  );159}...image.zoom-rotate.test.js
Source:image.zoom-rotate.test.js  
1/* global Feature, Scenario, DataTable, Data, locate */2const { initLabelStudio, serialize } = require("./helpers");3const assert = require("assert");4Feature("Zooming and rotating");5const IMAGE =6  "https://htx-misc.s3.amazonaws.com/opensource/label-studio/examples/images/nick-owuor-astro-nic-visuals-wDifg5xc9Z4-unsplash.jpg";7const BLUEVIOLET = {8  color: "#8A2BE2",9  rgbArray: [138, 43, 226],10};11const getConfigWithShape = (shape, props = "") => `12  <View>13    <Image name="img" value="$image" zoom="true" zoomBy="1.5" zoomControl="true" rotateControl="true"></Image>14    <${shape}Labels ${props} name="tag" toName="img">15        <Label value="Test" background="${BLUEVIOLET.color}"></Label>16    </${shape}Labels>17  </View>`;18const hScaleCoords = ([x, y], w, h) => {19  const ratio = w / h;20  return [x * ratio, y * ratio];21};22const rotateCoords = (point, degree, w, h) => {23  const [x, y] = point;24  if (!degree) return point;25  degree = (360 + degree) % 360;26  if (degree === 90) return hScaleCoords([h - y - 1, x], w, h);27  if (degree === 270) return hScaleCoords([y, w - x - 1], w, h);28  if (Math.abs(degree) === 180) return [w - x - 1, h - y - 1];29  return [x, y];30};31const shapes = [32  {33    shape: "KeyPoint",34    props: 'strokeWidth="5"',35    action: "clickKonva",36    regions: [37      {38        params: [100, 100],39      },40      {41        params: [200, 100],42      },43    ],44  },45  {46    shape: "Polygon",47    action: "clickPolygonPointsKonva",48    regions: [49      {50        params: [51          [52            [95, 95],53            [95, 105],54            [105, 105],55            [105, 95],56          ],57        ],58      },59      {60        params: [61          [62            [400, 10],63            [400, 90],64            [370, 30],65            [300, 10],66          ],67        ],68      },69    ],70  },71  {72    shape: "Rectangle",73    action: "dragKonva",74    regions: [75      {76        params: [95, 95, 10, 10],77      },78      {79        params: [400, 350, -50, -50],80      },81    ],82  },83  {84    shape: "Ellipse",85    action: "dragKonva",86    regions: [87      {88        params: [100, 100, 10, 10],89      },90      {91        params: [230, 300, -50, -30],92      },93    ],94  },95];96const shapesTable = new DataTable(["shape", "props", "action", "regions"]);97shapes.forEach(({ shape, props = "", action, regions }) => {98  shapesTable.add([shape, props, action, regions]);99});100Data(shapesTable).Scenario("Simple rotation", async function(I, AtImageView, current) {101  const params = {102    config: getConfigWithShape(current.shape, current.props),103    data: { image: IMAGE },104  };105  I.amOnPage("/");106  await I.executeAsyncScript(initLabelStudio, params);107  AtImageView.waitForImage();108  I.waitForVisible("canvas");109  I.see("0 Regions");110  const canvasSize = await AtImageView.getCanvasSize();111  for (let region of current.regions) {112    I.pressKey("u");113    I.pressKey("1");114    AtImageView[current.action](...region.params);115  }116  const standard = await I.executeScript(serialize);117  const rotationQueue = ["right", "right", "right", "right", "left", "left", "left", "left"];118  let degree = 0;119  let hasPixel = await AtImageView.hasPixelColor(100, 100, BLUEVIOLET.rgbArray);120  assert.equal(hasPixel, true);121  for (let rotate of rotationQueue) {122    I.click(locate("button").withDescendant(`[aria-label='rotate-${rotate}']`));123    degree += rotate === "right" ? 90 : -90;124    hasPixel = await AtImageView.hasPixelColor(125      ...rotateCoords([100, 100], degree, canvasSize.width, canvasSize.height).map(Math.round),126      BLUEVIOLET.rgbArray,127    );128    assert.equal(hasPixel, true);129    const result = await I.executeScript(serialize);130    for (let i = 0; i < standard.length; i++) {131      assert.deepEqual(standard[i].result, result[i].result);132    }133  }134});135Data(shapesTable).Scenario("Rotate zoomed", async function(I, AtImageView, current) {136  const params = {137    config: getConfigWithShape(current.shape, current.props),138    data: { image: IMAGE },139  };140  I.amOnPage("/");141  await I.executeAsyncScript(initLabelStudio, params);142  AtImageView.waitForImage();143  I.waitForVisible("canvas");144  I.see("0 Regions");145  const canvasSize = await AtImageView.getCanvasSize();146  for (let region of current.regions) {147    I.pressKey("u");148    I.pressKey("1");149    AtImageView[current.action](...region.params);150  }151  const rotationQueue = ["right", "right", "right", "right", "left", "left", "left", "left"];152  let degree = 0;153  const ZOOM = 3;154  AtImageView.setZoom(ZOOM, -100 * ZOOM, -100 * ZOOM);155  let hasPixel = await AtImageView.hasPixelColor(1, 1, BLUEVIOLET.rgbArray);156  assert.strictEqual(hasPixel, true);157  for (let rotate of rotationQueue) {158    I.click(locate("button").withDescendant(`[aria-label='rotate-${rotate}']`));159    degree += rotate === "right" ? 90 : -90;160    hasPixel = await AtImageView.hasPixelColor(161      ...rotateCoords([1, 1], degree, canvasSize.width, canvasSize.height).map(Math.round),162      BLUEVIOLET.rgbArray,163    );164    assert.strictEqual(hasPixel, true);165  }...canvas.js
Source:canvas.js  
...54   * @param {Number} x55   * @param {Number} y56   * @returns {Boolean}57   */58  hasPixel(x, y) {59    return x >= 0 && x < this.width && y >= 0 && y < this.heigth;60  }61  /**62   * Writes the Color 'color' at 'this.pixels[y][x]'.63   * Checks if the coordinates (x, y) and the Color 'color' are valid.64   * @param {Number} x65   * @param {Number} y66   * @param {Color} color67   * @returns {Canvas}68   */69  writePixel(x, y, color) {70    if (!this.hasPixel(x, y))71      throw new RayError('ray002', `Index (${x},${y}) out of bound`);72    if (!(color instanceof Color))73      throw new RayError('ray001', `${color} is not of type Color`);74    this.pixels[y][x] = color;75    return this;76  }77  /**78   * Returns the Color object at 'this.pixels[y][x]' if it exists.79   * @param {Number} x80   * @param {Number} y81   * @returns {Color}82   */83  pixelAt(x, y) {84    if (!this.hasPixel(x, y))85      throw new RayError('ray002', `Index (${x},${y}) out of bound`);86    if (!(this.pixels[y][x] instanceof Color))87      throw new RayError(88        'ray001',89        `${this.pixels[y][x]} is not of type Color`,90      );91    return this.pixels[y][x];92  }93  /**94   * Returns a PPM representation (including the appropriate header) of the canvas's pixels in string format.95   * Makes sure the last char of the PPM is a newline.96   * @returns {String}97   */98  toPPM() {...AtImageView.js
Source:AtImageView.js  
1/* global inject */2const { I } = inject();3const {4  waitForImage,5  clickKonva,6  polygonKonva,7  clickMultipleKonva,8  dragKonva,9  hasKonvaPixelColorAtPoint,10  whereIsPixel,11  getCanvasSize,12  setZoom,13} = require("../tests/helpers");14module.exports = {15  waitForImage() {16    I.executeAsyncScript(waitForImage);17  },18  async getCanvasSize() {19    const sizes = await I.executeAsyncScript(getCanvasSize);20    return sizes;21  },22  setZoom(scale, x, y) {23    I.executeAsyncScript(setZoom, scale, x, y);24  },25  /**26   * Click once on the main Stage27   * @param {number} x28   * @param {number} y29   */30  clickKonva(x, y) {31    I.executeAsyncScript(clickKonva, x, y);32  },33  /**34   * Click multiple times on the main Stage35   * @param {number[][]} points36   */37  clickPointsKonva(points) {38    I.executeAsyncScript(clickMultipleKonva, points);39  },40  /**41   * Click multiple times on the main Stage then close Polygon42   * @param {number[][]} points43   */44  clickPolygonPointsKonva(points) {45    I.executeAsyncScript(polygonKonva, points);46  },47  /**48   * Dragging between two points49   * @param {number} x50   * @param {number} y51   * @param {number} shiftX52   * @param {number} shiftY53   */54  dragKonva(x, y, shiftX, shiftY) {55    I.executeAsyncScript(dragKonva, x, y, shiftX, shiftY);56  },57  /**58   * Get  pixel color at point59   * @param {number} x60   * @param {number} y61   * @param {number[]} rgbArray62   * @param {number} tolerance63   */64  async hasPixelColor(x, y, rgbArray, tolerance = 3) {65    const hasPixel = await I.executeAsyncScript(hasKonvaPixelColorAtPoint, x, y, rgbArray, tolerance);66    return hasPixel;67  },68  // Only for debugging69  async whereIsPixel(rgbArray, tolerance = 3) {70    const points = await I.executeAsyncScript(whereIsPixel, rgbArray, tolerance);71    return points;72  },...TestFont.js
Source:TestFont.js  
1const CanvasPool = Phaser.Display.Canvas.CanvasPool;2var TestFont = function (familyName, testString) {3    // Get canvas from pool4    var canvas = CanvasPool.create();5    var context = canvas.getContext('2d');6    // Resize canvas7    var font = `8px ${familyName}`;8    context.font = font;9    var width = Math.ceil(context.measureText(testString).width);10    var baseline = width;11    var height = 2 * baseline;12    if ((width !== canvas.width) || (height !== canvas.height)) {13        canvas.width = width;14        canvas.height = height;15    }16    // Clear canvas17    context.fillStyle = '#000';18    context.fillRect(0, 0, width, height);19    // Draw text20    context.textBaseline = 'alphabetic';21    context.fillStyle = '#fff';22    context.font = font;23    context.fillText(testString, 0, baseline);24    // Check image data array25    var imagedata = context.getImageData(0, 0, width, height).data;26    var hasPixel = false;27    for (var i = 0, cnt = imagedata.length; i < cnt; i += 4) {28        if (imagedata[i] > 0) {29            hasPixel = true;30            break;31        }32    }33    // Recycle canvas34    CanvasPool.remove(canvas);35    return hasPixel;36}...Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#submit-button')5        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');6});Using AI Code Generation
1import {Selector} from 'testcafe';2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#submit-button');5    const articleHeader = await Selector('.result-content').find('h1');6    let headerText = await articleHeader.innerText;7});Using AI Code Generation
1import { Selector } from 'testcafe';2test('My test', async t => {3        .click('#populate')4        .click('#submit-button');5    const table = Selector('#results-table');6    const hasPixel = await table.hasChildElement('td', { text: 'Pixel 2' });7});8import { Selector } from 'testcafe';9test('My test', async t => {10        .click('#populate')11        .click('#submit-button');12    const table = Selector('#results-table');13    const hasProperty = await table.hasElementProperty('rows.length', 5);14});15import { Selector } from 'testcafe';Using AI Code Generation
1import { Selector } from 'testcafe';2test('My test', async t => {3    const developerNameInput = Selector('#developer-name');4    const osOption            = Selector('label').withText('Linux');5    const submitButton        = Selector('#submit-button');6        .typeText(developerNameInput, 'John Smith')7        .click(osOption)8        .click(submitButton)9        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');10});11import { Selector } from 'testcafe';12test('My test', async t => {13    const developerNameInput = Selector('#developer-name');14    const osOption            = Selector('label').withText('Linux');15    const submitButton        = Selector('#submit-button');16        .expect(Selector('title').innerText).eql('Example page')17        .typeText(developerNameInput, 'John Smith')18        .click(osOption)19        .expect(Selector('title').innerText).eql('Example page')20        .click(submitButton)21        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');22});23import { Selector } from 'testcafe';24test('My test', async t => {25        .click('#populate')26        .expect(Selector('#developer-name').value).eql('Peter Parker')27        .expect(Selector('#windows').checked).notOk()28        .expect(Selector('#macos').checked).ok()29        .expect(Selector('#linux').checked).ok();30});31import { Selector } from 'testcafe';32test('My test', async t => {33    const slider = Selector('#slider');34        .expect(slider.value).eql(5)35        .click(slider)36        .pressKey('right')37        .expect(slider.value).eql(6);38});Using AI Code Generation
1import { Selector } from 'testcafe';2test('My Test', async t => {3    const checkBox = Selector('#remote-testing');4        .expect(checkBox.hasAttribute('checked')).notOk()5        .click(checkBox)6        .expect(checkBox.hasAttribute('checked')).ok();7});Using AI Code Generation
1import { Selector } from 'testcafe';2test('My test', async t => {3    const element = Selector('#my-element');4    const isElementVisible = await element.visible;5    await t.expect(isElementVisible).ok();6});Using AI Code Generation
1import {Selector} from 'testcafe';2test('Check if a pixel is on the page', async t => {3    const pixelColor = await Selector('#submit-button').hasPixel({4    });5    await t.expect(pixelColor).ok();6});7Contributions are welcome. Please submit a pull request to the [GitHub repository](Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
