Best JavaScript code snippet using testcafe
test.js
Source:test.js
...541 if (config.useLocalBrowsers && config.useHeadlessBrowsers) {542 it('Should take a full page screenshot via API', function () {543 return runTests('./testcafe-fixtures/take-full-page-screenshot.js', 'API', { setScreenshotPath: true })544 .then(function () {545 return assertionHelper.checkScreenshotFileFullPage(false, 'custom');546 })547 .then(function (result) {548 expect(result).eql(true);549 });550 });551 it('Should take a full page screenshot via Runner', function () {552 return runTests('./testcafe-fixtures/take-full-page-screenshot.js', 'Runner', {553 setScreenshotPath: true,554 screenshotsFullPage: true555 })556 .then(function () {557 return assertionHelper.checkScreenshotFileFullPage(false, 'custom');558 })559 .then(function (result) {560 expect(result).eql(true);561 });562 });563 it('Should take a screenshot on fail', function () {564 return runTests('./testcafe-fixtures/take-full-page-screenshot.js', 'Screenshot on fail', {565 shouldFail: true,566 setScreenshotPath: true,567 screenshotsFullPage: true,568 screenshotsOnFails: true569 })570 .catch(function (errs) {571 expect(errs[0]).to.contains('screenshot on fail');572 return assertionHelper.checkScreenshotFileFullPage(true);573 });574 });575 }...
assertion-helper.js
Source:assertion-helper.js
1const expect = require('chai').expect;2const globby = require('globby');3const path = require('path');4const fs = require('fs');5const { isFunction } = require('lodash');6const del = require('del');7const config = require('./config.js');8const { readPngFile } = require('../../lib/utils/promisified-functions');9const parseUserAgent = require('../../lib/utils/parse-user-agent');10const SCREENSHOTS_PATH = config.testScreenshotsDir;11const THUMBNAILS_DIR_NAME = 'thumbnails';12const ERRORS_DIR_NAME = 'errors';13const TASK_DIR_RE = /\d{4,4}-\d{2,2}-\d{2,2}_\d{2,2}-\d{2,2}-\d{2,2}/;14const SCREENSHOT_FILE_NAME_RE = /[\\/]\d+.png$/;15const CUSTOM_SCREENSHOT_FILE_NAME_RE = /\.png$/;16const TEST_DIR_NAME_RE = /test-\d+/;17const RUN_DIR_NAME_RE = /run-\d+/;18const GREEN_PIXEL = [0, 255, 0, 255];19const RED_PIXEL = [255, 0, 0, 255];20const VIDEOS_PATH = config.testVideosDir;21const VIDEO_FILES_GLOB = path.join(VIDEOS_PATH, '**', '*');22function hasPixel (png, pixel, x, y) {23 const baseIndex = (png.width * y + x) * 4;24 return png.data[baseIndex] === pixel[0] &&25 png.data[baseIndex + 1] === pixel[1] &&26 png.data[baseIndex + 2] === pixel[2] &&27 png.data[baseIndex + 3] === pixel[3];28}29function getScreenshotFilesCount (dir, customPath) {30 const list = fs.readdirSync(dir);31 const screenshotRegExp = customPath ? CUSTOM_SCREENSHOT_FILE_NAME_RE : SCREENSHOT_FILE_NAME_RE;32 let results = 0;33 let stat = null;34 let filePath = null;35 list.forEach(function (file) {36 filePath = path.join(dir, file);37 stat = fs.statSync(filePath);38 if (stat && stat.isDirectory() && file === THUMBNAILS_DIR_NAME)39 results += getScreenshotFilesCount(filePath, customPath);40 else if (screenshotRegExp.test(filePath))41 results++;42 });43 return results;44}45function checkScreenshotFileCropped (filePath) {46 return readPngFile(filePath)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) {82 exists = false;83 }84 return exists;85}86function checkTestDir (testDirPath, forError, expectedSubDirCount, expectedScreenshotCount) {87 const subDirs = fs88 .readdirSync(testDirPath)89 .filter(function (file) {90 return isDirExists(path.join(testDirPath, file));91 });92 if (subDirs.length !== expectedSubDirCount)93 return false;94 let dirPath = null;95 return subDirs.every(function (dir) {96 dirPath = forError ? path.join(testDirPath, dir, ERRORS_DIR_NAME) : path.join(testDirPath, dir);97 return getScreenshotFilesCount(dirPath) === expectedScreenshotCount;98 });99}100function checkScreenshotImages (forError, customPath, predicate, expectedScreenshotsCount = config.browsers.length) {101 if (!isDirExists(SCREENSHOTS_PATH))102 return false;103 const taskDirs = fs.readdirSync(SCREENSHOTS_PATH);104 if (!taskDirs || !taskDirs[0] || taskDirs.length !== 1)105 return false;106 const taskDirPath = path.join(SCREENSHOTS_PATH, taskDirs[0]);107 let list = [];108 if (forError) {109 const testDirs = fs.readdirSync(taskDirPath);110 if (!testDirs || !testDirs[0] || testDirs.length !== 1)111 return false;112 const testDirPath = path.join(taskDirPath, testDirs[0]);113 const browserDirs = fs.readdirSync(testDirPath);114 browserDirs.forEach(function (browserDir) {115 const errorDirPath = path.join(testDirPath, browserDir, 'errors');116 const screenshotFiles = fs.readdirSync(errorDirPath);117 const screenshotPaths = screenshotFiles.map(function (screenshotFile) {118 return path.join(errorDirPath, screenshotFile);119 });120 list = list.concat(screenshotPaths);121 });122 }123 else {124 if (taskDirPath.indexOf(customPath) < 0)125 return false;126 list = fs.readdirSync(taskDirPath).map(function (screenshotFile) {127 return path.join(taskDirPath, screenshotFile);128 });129 }130 if (list.length < config.browsers.length)131 return false;132 list = list.filter(function (filePath) {133 return filePath.match(CUSTOM_SCREENSHOT_FILE_NAME_RE);134 });135 return Promise136 .all(list.map(function (filePath) {137 return predicate(filePath);138 }))139 .then(function (checkResults) {140 let actualScreenshotsCount = 0;141 for (let i = 0; i < checkResults.length; i++)142 actualScreenshotsCount += checkResults[i] ? 1 : 0;143 return actualScreenshotsCount === expectedScreenshotsCount;144 });145}146exports.errorInEachBrowserContains = function errorInEachBrowserContains (testErrors, message, errorIndex) {147 if (testErrors instanceof Error)148 throw testErrors;149 // NOTE: if errors are the same in different browsers150 if (Array.isArray(testErrors))151 expect(testErrors[errorIndex]).contains(message);152 //NOTE: if they are different153 else {154 Object.keys(testErrors).forEach(function (key) {155 expect(testErrors[key][errorIndex]).contains(message);156 });157 }158};159exports.errorInEachBrowserContainsRegExp = function errorInEachBrowserContains (testErrors, messageRE, errorIndex) {160 if (testErrors instanceof Error)161 throw testErrors;162 // NOTE: if errors are the same in different browsers163 if (Array.isArray(testErrors))164 expect(messageRE.test(testErrors[errorIndex])).equals(true);165 //NOTE: if they are different166 else {167 Object.keys(testErrors).forEach(function (key) {168 expect(messageRE.test(testErrors[key][errorIndex])).equals(true);169 });170 }171};172exports.errorInEachBrowserNotContains = function errorInEachBrowserNotContains (testErrors, message, errorIndex) {173 if (testErrors instanceof Error)174 throw testErrors;175 // NOTE: if errors are the same in different browsers176 if (Array.isArray(testErrors))177 expect(testErrors[errorIndex]).not.contains(message);178 //NOTE: if the are different179 else {180 Object.keys(testErrors).forEach(function (key) {181 expect(testErrors[key][errorIndex]).not.contains(message);182 });183 }184};185exports.isScreenshotDirExists = function () {186 return isDirExists(SCREENSHOTS_PATH);187};188exports.checkScreenshotsCreated = function ({ forError, customPath, screenshotsCount, runDirCount, browsersCount, baseDir }) {189 const expectedSubDirCount = browsersCount || config.browsers.length;190 const expectedScreenshotCount = screenshotsCount || 2;191 baseDir = baseDir || SCREENSHOTS_PATH;192 if (!isDirExists(baseDir))193 return false;194 const taskDirs = fs.readdirSync(baseDir);195 if (!taskDirs || !taskDirs[0] || taskDirs.length !== 1)196 return false;197 const taskDirPath = path.join(baseDir, taskDirs[0]);198 if (customPath) {199 const customDirExists = taskDirPath.includes(customPath);200 const hasScreenshots = getScreenshotFilesCount(taskDirPath, customPath) ===201 expectedScreenshotCount * expectedSubDirCount;202 return customDirExists && hasScreenshots;203 }204 if (!TASK_DIR_RE.test(taskDirs[0]))205 return false;206 const testDirs = fs.readdirSync(taskDirPath);207 if (!testDirs || !testDirs.length || testDirs.length !== 1)208 return false;209 let basePath = null;210 let dirs = null;211 let dirNameRE = null;212 let dirPath = null;213 if (runDirCount) {214 basePath = path.join(taskDirPath, testDirs[0]);215 dirs = fs.readdirSync(basePath);216 dirNameRE = RUN_DIR_NAME_RE;217 if (!dirs || !dirs.length || dirs.length !== runDirCount)218 return false;219 }220 else {221 basePath = taskDirPath;222 dirs = testDirs;223 dirNameRE = TEST_DIR_NAME_RE;224 }225 return dirs.every(function (dir) {226 if (!dirNameRE.test(dir))227 return false;228 dirPath = path.join(basePath, dir);229 return checkTestDir(dirPath, forError, expectedSubDirCount, expectedScreenshotCount);230 });231};232exports.checkScreenshotsCropped = function (forError, customPath) {233 return checkScreenshotImages(forError, customPath, checkScreenshotFileCropped);234};235exports.checkScreenshotIsNotWhite = function (forError, customPath) {236 return checkScreenshotImages(forError, customPath, checkScreenshotFileIsNotWhite);237};238exports.checkScreenshotFileFullPage = function (forError, customPath) {239 return checkScreenshotImages(forError, customPath, checkScreenshotFileFullPage);240};241exports.isScreenshotsEqual = function (customPath, referenceImagePathGetter) {242 return checkScreenshotImages(false, customPath, function (screenshotFilePath) {243 const screenshotContent = fs.readFileSync(screenshotFilePath);244 const referenceImagePath = isFunction(referenceImagePathGetter)245 ? referenceImagePathGetter(screenshotFilePath)246 : referenceImagePathGetter;247 const referenceImageContent = fs.readFileSync(referenceImagePath);248 return screenshotContent.equals(referenceImageContent);249 });250};251exports.checkScreenshotsDimensions = function (dimensions, screenshotCount) {252 return checkScreenshotImages(false, '', function (screenshotFilePath) {253 return readPngFile(screenshotFilePath)254 .then(png => {255 return dimensions.width === png.width && dimensions.height === png.height;256 });257 }, screenshotCount);258};259function removeDir (dirPath) {260 if (isDirExists(dirPath))261 return del(dirPath);262 return Promise.resolve();263}264exports.removeScreenshotDir = (dir = SCREENSHOTS_PATH) => removeDir(dir);265exports.removeVideosDir = () => removeDir(VIDEOS_PATH);266exports.getVideoFilesList = () => {267 return globby(VIDEO_FILES_GLOB, { nodir: true });268};269exports.checkUserAgent = function (errs, alias) {270 const isErrorsArray = config.currentEnvironment.browsers.length === 1 && Array.isArray(errs);271 if (!isErrorsArray)272 errs = errs[alias];273 if (!isErrorsArray && !errs)274 throw new Error('Error for "' + alias + '" haven\'t created');275 const parsedUA = parseUserAgent(errs[0]);276 const prettyUA = parsedUA.prettyUserAgent.toLowerCase();277 // NOTE: the "ie" alias corresponds to the "internet explorer" lowered part of a compact user agent string (GH-481)278 const expectedBrowserName = alias === 'ie' ? 'internet explorer' : alias;279 expect(prettyUA.indexOf(expectedBrowserName)).eql(0, prettyUA + ' doesn\'t start with "' + expectedBrowserName + '"');280};281exports.SCREENSHOTS_PATH = SCREENSHOTS_PATH;...
Using AI Code Generation
1import { ClientFunction } from 'testcafe';2const getDocumentHeight = ClientFunction(() => Math.max(3));4test('Screenshot', async t => {5 .resizeWindow(1920, 1080)6 .takeScreenshot('screenshot.png');7 const height = await getDocumentHeight();8 await t.resizeWindow(1920, height);9 await t.takeScreenshot('screenshot-full.png');10});11test('Screenshot', async t => {12 .resizeWindow(1920, 1080)13 .takeScreenshot('screenshot.png');14 const height = await getDocumentHeight();15 await t.resizeWindow(1920, height);16 await t.takeScreenshot('screenshot-full.png');17});18test('Screenshot', async t => {19 .resizeWindow(1920, 1080)20 .takeScreenshot('screenshot.png');21 const height = await getDocumentHeight();22 await t.resizeWindow(1920, height);23 await t.takeScreenshot('screenshot-full.png');24});25test('Screenshot', async t => {26 .resizeWindow(1920, 1080)27 .takeScreenshot('screenshot.png');28 const height = await getDocumentHeight();29 await t.resizeWindow(1920, height);30 await t.takeScreenshot('screenshot-full.png');31});32test('Screenshot', async t => {33 .resizeWindow(1920, 1080)34 .takeScreenshot('screenshot.png');35 const height = await getDocumentHeight();36 await t.resizeWindow(1920, height);37 await t.takeScreenshot('screenshot-full.png');38});39test('Screenshot', async t => {40 .resizeWindow(1920, 1080)41 .takeScreenshot('screenshot.png');
Using AI Code Generation
1import { Selector } from 'testcafe';2import { checkScreenshotFileFullPage } from 'testcafe-blink-diff';3test('My first test', async t => {4 .click(Selector('label').withText('I have tried TestCafe'))5 .typeText('#developer-name', 'John Smith')6 .click('#submit-button')7 .takeScreenshot('test.png');8 await checkScreenshotFileFullPage(t, 'test.png');9});
Using AI Code Generation
1import { Selector } from 'testcafe';2import { checkScreenshotFileFullPage } from './checkScreenshotFileFullPage';3test('My first test', async t => {4 .typeText('#developer-name', 'John Smith')5 .click('#submit-button')6 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');7 await checkScreenshotFileFullPage('screenshot.png');8});9import { t } from 'testcafe';10import { ClientFunction } from 'testcafe';11export async function checkScreenshotFileFullPage(fileName) {12 const getDocumentHeight = ClientFunction(() => document.documentElement.scrollHeight);13 const documentHeight = await getDocumentHeight();14 await t.takeScreenshot({ path: fileName, fullPage: true, scrollTargetHeight: documentHeight });15}16{17 "scripts": {18 },19 "dependencies": {20 }21}
Using AI Code Generation
1import { Selector } from 'testcafe';2import { checkScreenshotFileFullPage } from './checkScreenshotFileFullPage';3test('My first test', async t => {4 .typeText('#developer-name', 'John Smith')5 .click('#submit-button')6 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');7 await checkScreenshotFileFullPage('screenshot.png');8});9import { t } from 'testcafe';10import { ClientFunction } from 'testcafe';11export async function checkScreenshotFileFullPage(fileName) {12 const getDocumentHeight = ClientFunction(() => document.documentElement.scrollHeight);13 const documentHeight = await getDocumentHeight();14 await t.takeScreenshot({ path: fileName, fullPage: true, scrollTargetHeight: documentHeight });15}16{17 "scripts": {18 },19 "dependencies": {20 }21}
Using AI Code Generation
1test('My first test', async t => {2 .typeText('#lst-ib', 'Hello, TestCafe!')3 .click('#tsf > div.tsf-p > div.jsb > center > input[type="submit"]:nth-child(1)');4 await t.checkScreenshotFileFullPage('test.png', {fullPage: true});5});6test('Test', async t => {7 .typeText('#lst-ib', 'Hello, TestCafe!')8 .click('#tsf > div.tsf-p > div.jsb > center > input[type="submit"]:nth-child(1)')9 .expect('#tsf > div.tsf-p > div.jsb > center > input[type="submit"]:nth-child(1)').ok();10});11test('Test', async t => {12 .typeText('#lst-ib', 'Hello, TestCafe!')13 .click('#tsf > div.tsf-p > div.jsb > center > input[type="submit"]:nth-child(1)')14 .expect('#tsf > div.tsf-p > div.jsb > center > input[type="submit"]:nth-child(1)').ok();15});16test('Test', async t => {17 .typeText('#lst-ib', 'Hello, TestCafe!')18 .click('#tsf > div.tsf-p > div.jsb > center > input[type="submit"]:nth-child(1)')19 .expect('#tsf > div.tsf-p > div.jsb > center > input[type="submit"]:nth-child(1)').ok();20});21test('Test', async t => {
Using AI Code Generation
1import { Selector } from 'testcafe';2import { checkScreenshotFileFullPage } from './screenshot.js';3test('Testcafe Screenshot Test', async t => {4 .typeText('input[name="q"]', 'testcafe')5 .pressKey('enter');6 const result = Selector('div.g');7 .expect(result.exists).ok()8 .wait(1000);9 await checkScreenshotFileFullPage('testcafe.png');10});11import { Selector } from 'testcafe';12import { ClientFunction } from 'testcafe';13export async function checkScreenshotFileFullPage(fileName) {14 const screenshotPath = './screenshots/' + fileName;15 const getDocumentHeight = ClientFunction(() => {16 const body = document.body;17 const html = document.documentElement;18 return Math.max(
Using AI Code Generation
1import { Selector } from 'testcafe';2import { checkScreenshotFileFullPage } from 'testcafe-screenshot';3test('Google', async t => {4 await checkScreenshotFileFullPage(t, Selector('body'), 'google');5});6import { ClientFunction } from 'testcafe';7export const checkScreenshotFileFullPage = async (t, target, name) => {8 await t.takeScreenshot({9 path: `./screenshots/${name}.png`10 });11};
Using AI Code Generation
1import { Selector } from 'testcafe';2import { checkScreenshotFileFullPage } from 'testcafe-screenshot-file-diff';3const testcafe = require('testcafe');4test('My Test', async t => {5 .typeText('input[name="q"]', 'testcafe')6 .click('input[name="btnK"]');7 await checkScreenshotFileFullPage(t, 'testcafe.png');8});
Using AI Code Generation
1import { Selector } from 'testcafe';2import { checkScreenshotFileFullPage } from 'testcafe-visual-regression-plugin';3test('Check visual regression', async t => {4 .expect(Selector('h1').innerText).eql('Example Domain')5 .expect(checkScreenshotFileFullPage('test.png')).ok();6});
Using AI Code Generation
1import { Selector } from 'testcafe';2import { checkScreenshotFileFullPage } from 'testcafe-visual-regression-plugin';3test('Check visual regression', async t => {4 .expect(Selector('h1').innerText).eql('Example Domain')5 .expect(checkScreenshotFileFullPage('test.png')).ok();ight6});7 });8 const getDocumentWidth = ClientFunction(() => {9 const body = document.body;10 const html = document.documentElement;11 return Math.max(12 );13 });14 const documentWidth = await getDocumentWidth();15 const documentHeight = await getDocumentHeight();16 await t.takeScreenshot({17 selector: Selector('body'),18 crop: {19 }20 });21}22await t.takeScreenshot({23 selector: Selector('body'),
Using AI Code Generation
1import { Selector } from 'testcafe';2import { checkScreenshotFileFullPage } from 'testcafe-screenshot';3test('Google', async t => {4 await checkScreenshotFileFullPage(t, Selector('body'), 'google');5});6import { ClientFunction } from 'testcafe';7export const checkScreenshotFileFullPage = async (t, target, name) => {8 await t.takeScreenshot({9 path: `./screenshots/${name}.png`10 });11};
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!!