Search This Blog

Thursday, May 27, 2021

Test Cafe

 What is Test Cafe

  • Allows you to write tests using TypeScript or JavaScript
  • End-to-end free and open source automation tool which is used to test web applications
  • Works on all popular environments such as Windows, MacOS, and Linux
  • Easy to install feature in a single command
  • Does not depend on Selenium or other testing software

How to Install

npm install -g testcafe


Sample Program

import { Selector } from 'testcafe';

fixture `Getting Started`// declare the fixture

    .page `https://devexpress.github.io/testcafe/example`;  // specify the start page

//then create a test and place your code there

test('My first test', async t => {

    await t

        .wait(2000)

        .typeText('#developer-name', 'John Smith')

        .click('#submit-button')

        // Use the assertion to check if the actual header text is equal to the expected one

        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!')

        .wait(2000);

});


How to Run

testcafe chrome test1.js


Fiture: TestCafe tests are organized into categories called fixuture. Fixture can be compared with Module where test cases related to similar functionalities are maintained.

Declare Fixture

fixture ( fixtureName )

fixture `fixtureName`


Test: test case/functionality to be verified

test ( 'testName', fn(t))


Test Controller: object t exposes the test API's methods. Thus it is passed to each function.


Page can be written in two ways

1. fixture `fixtureName`

    .page `PageUrl`;

2. test

    .page `PageUrl`

('testName', fn(t));



Actions


Browser 

Returns information about the current user agent: the operating system, platform type, browser, engine, etc.

Syntax:

t.browser

eg.

if (t.browser.name !== 'Chrome')

        await t.expect(Selector('div').withText('Browser not supported').visible).ok();


ClearUpload

Removes all file paths from the specified file upload input.

Syntax:

t.clearUpload(selector)

eg.

.setFilesToUpload('#upload-input', [

            './uploads/1.jpg',

            './uploads/2.jpg',

            './uploads/3.jpg'

        ])

        .clearUpload('#upload-input')



OpenWindow

Opens a new browser window.

Syntax:

t.openWindow( url )

eg.

.openWindow('http://devexpress.github.io/testcafe')

        .openWindow('./documentation');



CloseWindow

Closes a browser window. Each call of the t.closeWindow method closes the active window:

Syntax:

t.closeWindow([windowDescriptor])

eg.1

t.openWindow('https://devexpress.github.io/testcafe');

        .openWindow('https://devexpress.com');

        .closeWindow()

        .closeWindow();

        eg.2

         const testcafe =  await t.openWindow('https://devexpress.github.io/testcafe');

        await t.openWindow('https://devexpress.com');

        const devexpress = await t.getCurrentWindow();

        await t.closeWindow(devexpress)

        .closeWindow(testcafe);



Debug

Pauses the test and allows you to use the browser’s developer tools.

Syntax:

t.debug()

eg.

.debug()



DoubleClick

Double-clicks an element on a page.

Syntax:

t.doubleClick(selector [, options])

eg.

const dialog = Selector('#dialog');

.doubleClick('#thumbnail')

        .expect(dialog.visible).ok();



Drag

Drags an element to a specified offset.

Syntax:

t.drag(selector, dragOffsetX, dragOffsetY [, options])

eg.

.drag('.ui-slider-handle', 360, 0, { offsetX: 10, offsetY: 10 })

.expect(slider.value).eql(7);



DragToElement

Drags an element onto another web page element.

Syntax:

t.dragToElement(selector, destinationSelector [, options])

eg.

const designSurfaceItems = Selector('.design-surface').find('.items');

.dragToElement('.toolbox-item.text-input', '.design-surface')

.expect(designSurfaceItems.count).gt(0);



Eval

Creates a client function and executes it immediately (without saving).

Always place eval in a separate call.

Syntax:

t.eval(fn [, options])

eg.1

const docURI = await t.eval(() => document.documentURI);

eg.2

await t.eval(() => location.reload(true));



Expect

This method accepts the actual value.

Syntax:

await t.expect(doSomethingAsync()).ok('check that a promise is returned', { allowUnawaitedPromise: true });

eg.1

.expect(developerNameInput.value).eql('', 'input is empty')

eg.2

.expect(developerNameInput.value).notEql('', 'input is empty')

eg.3

.expect(developerNameInput.value).contains('Peter', 'input contains text "Peter"');

eg.4

.expect(Selector('#element').exists).ok();

eg.5

.expect(Selector('#element').exists).notOk();

eg.6

.expect(Selector('#element').getAttribute('attr')).typeOf('string');

eg.7

.expect(Selector('#element').getAttribute('attr')).typeOf('string');

eg.8

.expect(Selector('#element').clientWidth).gt(300);

eg.9

.expect(Selector('#element').clientWidth).gte(300);

eg.10

.expect(Selector('#element').clientWidth).lt(300);

eg.11

.expect(Selector('#element').clientWidth).lte(300);

eg.12

.expect(Selector('#element').scrollTop).within(300, 400);

eg.13

.expect(Selector('#element').scrollTop).within(300, 400);

eg.14

.expect(developerNameInput.value).match(/\.com/);

eg.15

.expect(developerNameInput.value).notMatch(/\.com/);



getBrowserConsoleMessages

Returns messages posted to the browser console. Cannot be chained with other methods of the test controller.

Syntax:

t.getBrowserConsoleMessages()

eg.

// check-prop-types.js

import { t } from 'testcafe';

export default async function () {

    const { error } = await t.getBrowserConsoleMessages();

    await t.expect(error[0]).notOk();

}

// test.js

import { Selector } from 'testcafe';

import checkPropTypes from './check-prop-types';

fixture `react example`

    .page `http://localhost:8080/`  // https://github.com/mzabriskie/react-example

    .afterEach(() => checkPropTypes());

test('test', async t => {

    await t

        .typeText(Selector('.form-control'), 'devexpress')

        .click(Selector('button').withText('Go'))

        .click(Selector('h4').withText('Organizations'));

});

Note: This method can be used with below fields

error (Array of String) Error messages printed in the console.

warn (Array of String) Warning messages printed in the console.

log (Array of String) Log messages printed in the console.

info (Array of String) Information messages printed in the console.


 

getCurrentWindow

Retrieves a window descriptor that corresponds to the active window.

Syntax:

t.getCurrentWindow()

eg.

await t.openWindow('https://devexpress.com');

    const devexpress = await t.getCurrentWindow();

    await t.closeWindow(devexpress);


 

hover

Hovers the mouse pointer over a web page element.

Syntax:

t.hover(selector [, options])

eg.

const comboBox = Selector('.combo-box');

.hover(comboBox)



maximizeWindow

Maximizes the browser window.

Syntax:

        t.maximizeWindow()

eg.

.maximizeWindow()



navigateTo

Navigates to the specified URL.

Syntax:

t.navigateTo(url)

        eg.

.navigateTo('http://devexpress.github.io/testcafe')

.navigateTo('file:///user/my-website/index.html')

        .navigateTo('../my-project/index.html')



openWindow

Opens a new browser window.

Syntax:

eg.

t.openWindow( url )

.openWindow('http://devexpress.github.io/testcafe')

.openWindow('./documentation');



pressKey

Presses the specified keyboard keys. 

Syntax:

t.pressKey(keys [, options])

eg.

.pressKey('h o m e home r i g h t right r i g h t right',{ speed: 0.1 })

.pressKey('ctrl+a d e v 1 s p a c e space b a c k s p a c e backspace ctrl+a',{ speed: 1 })

.pressKey('ctrl+a D E V 2 e n d end l e f t left c t r l + a ctrl+a delete a a a a backspace delete',{ speed: 1 })

.pressKey('ctrl+a backspace',{ speed: 1 })

Below are the various actions we can perform by using presskey

  • 'backspace'
  • 'tab'
  • 'enter'
  • 'capslock'
  • 'esc'
  • 'space'
  • 'pageup'
  • 'pagedown'
  • 'end'
  • 'home'
  • 'left'
  • 'right'
  • 'up'
  • 'down'
  • 'ins'
  • 'delete'

option: speed valued can be between 0.01 to 1


 

resizeWindow

Resizes a window to fit the parameters entered by user

Syntax

t.resizeWindow(width, height)

eg.

.resizeWindow(200, 100)


 

resizeWindowToFitDevice

Resizes the window to fit the screen of the specified mobile device.

Syntax

t.resizeWindowToFitDevice(deviceName [, options])

eg.

.resizeWindowToFitDevice('Sony Xperia Z', {

            portraitOrientation: true

        })

    Remark

    device name is configured in viewport-sizes.json file like below

    "sonyxperiaz": {

    "portraitWidth": 360,

    "landscapeWidth": 640,

    "name": "Sony Xperia Z"

  },

  All list of device name

  https://github.com/DevExpress/device-specs/blob/master/viewport-sizes.json


 

rightClick

Right-clicks an element on a page.

Syntax

t.rightClick(selector [, options])

eg.

.rightClick('#cell-1-1')


 

scroll

Scrolls the target element to a specified position. If no target is specified, the document body is scrolled.

Syntax

t.scroll([target,] posX, posY[, options])

and

t.scroll([target,] position[, options])

eg.

const container = Selector('#container');

.scroll(container, 'bottomRight');


 

scrollBy

Scrolls the target element by the specified number of pixels. If no target is specified, the document body is scrolled.

Syntax

t.scrollBy([target,] x, y[, options])

eg.

.scrollBy(500, -200);


 

scrollIntoView

Scrolls parent containers of the target element until the element is in the viewport.

Syntax

.scrollIntoView(target [, options])

eg.

const target = Selector('#target');

.scrollIntoView(target);


 

selectEditableContent

Selects editable content on a web page.

Syntax

t.selectEditableContent(startSelector, endSelector [, options])

eg.

.selectEditableContent('#foreword', '#chapter-3')


 

selectText

Selects text in input elements of various types.

Syntax

t.selectText(selector [, startPos] [, endPos] [, options])

eg.

const developerNameInput = Selector('#developer-name');

.selectText(developerNameInput, 7, 1);


 

selectTextAreaContent

Selects <textarea> content. 

Syntax

t.selectTextAreaContent(selector [, startLine] [, startPos] [, endLine] [, endPos] [, options])

eg.

const commentTextArea = Selector('#comments');

.selectTextAreaContent(commentTextArea, 0, 5, 2, 10);


 

setFilesToUpload

Sets files to upload. Emulates a user’s selection in the browser’s ‘Choose File’ dialog.

Syntax

t.setFilesToUpload(selector, filePath)

eg.

.setFilesToUpload('#upload-input', [

            './uploads/1.jpg',

            './uploads/2.jpg',

            './uploads/3.jpg'

        ])

        .click('#upload-button');


 

setPageLoadTimeout

Defines the time passed after the DOMContentLoaded event within which the window.load event should be raised.

Syntax

t.setPageLoadTimeout(duration)

eg.

.setPageLoadTimeout(0)


 

setTestSpeed

Specifies the test execution speed.

Syntax

t.setTestSpeed(factor)

eg.

.setTestSpeed(0.1)


 

switchToIframe

Switches to an <iframe>.

Syntax

t.switchToIframe(selector)

eg.

.switchToIframe('#iframe-1')


 

switchToMainWindow

Switches the test’s browsing context from an <iframe> back to the main window.

Syntax

t.switchToMainWindow()

eg.

.switchToIframe('#iframe-1')

        .click('#button-in-iframe-1')

        .switchToMainWindow()

        .click('#button-in-main-window');


 

switchToParentWindow

Activates the window that launched or was active when the active window was launched.

Syntax

t.switchToParentWindow()

eg.

.openWindow('https://devexpress.com')

        .switchToParentWindow();



switchToPreviousWindow

Activates the previously active window.

Syntax

t.switchToPreviousWindow()

eg.

.openWindow('https://devexpress.com')

        .switchToPreviousWindow();


 

switchToWindow

Switches to a specific browser window.

Syntax

t.switchToWindow(windowDescriptor)

t.switchToWindow(filterFn)

eg.

const homepage = await t.getCurrentWindow();

        const documentation = await t.openWindow('http://devexpress.github.io/testcafe/documentation');

        await t.switchToWindow(homepage)

        .switchToWindow(documentation);


 

takeElementScreenshot

Takes a screenshot of the specified page element.

Syntax

t.takeElementScreenshot(selector[, path][, options])

eg.

.takeElementScreenshot(Selector('fieldset').nth(1), 'my-fixture/important-features.png')


 

takeScreenshot

Takes screenshot of the entire page.

Syntax

t.takeScreenshot([options])

eg.

.takeScreenshot({

            path:     'my-fixture/thank-you-page.png',

            fullPage: true

        });


 

typeText

Types the specified text into an input element.

Syntax

t.typeText(selector, text [, options])

eg.

.typeText(nameInput, 'Peter')

        .typeText(nameInput, 'Paker', { replace: true })

        .typeText(nameInput, 'r', { caretPos: 2 })

        .typeText(color, '#FF8040')

        .typeText(datetime, '2017-11-03T05:00')

        .typeText(date, '2017-11-03')

        .typeText(time, '15:30')

        .typeText(month, '2017-08')

        .typeText(range, '80');


 

useRole

Activates the role.

Syntax

t.useRole(role)

eg.

const registeredUser = Role('http://example.com/login', async t => {

    await t

        .typeText('#login', 'username')

        .typeText('#password', 'pa$$w0rd')

        .click('#sign-in');

});

test('My Test', async t => {

    await t

        .useRole(registeredUser)

        .expect(Selector('#avatar').visible).ok();


 

wait

Pauses a test for a specified period of time.

Syntax

t.wait(timeout)

eg.

.wait(1000)





















No comments:

Post a Comment


This is a User Friendly Blog.
Simple Interface and Simple Controls are used.
Post your comments so i can modify blog regarding your wish.