TestCafe Basics: Top 5 Actions to Interact with the Page
A couple of months ago, I began my journey of implementing testing into my projects and working with the automation framework TestCafe, and wrote an introductory blog that you can check out here. Today, I’m going to expand on what I discussed then and show y’all 5 important actions any TestCafe user should know.
To start, I’m going to remind you what the syntax of a TestCafe test looks like:
test('name of your test here', async t => { // testcafe actions go in here })
Pretty simple. So, the actions are what we put inside of the function to instruct the test what to do on the web page. Most of them are pretty self explanatory, but I’m going to break down 5 of them now!
Click
Use this action when you want the test to click an element on the page. First step is to use the TestCafe Selector to find the element you are looking for, and then call on that like so:
test('name of your test here', async t => { const button = Selector('#submit-button')
await t.click(button)})
I’m not going to go into Selectors too much, but you can find out more about them here. As I mentioned in my previous blog, make sure you import Selector at the top of your file, and then use a CSS selector to grab the element you seek. IDs are definitely the easiest to use in this situation!
Type Text
Like click, type text is pretty explanatory. The most frequent time it is used it is to make sure forms are working properly:
test('name of your test here', async t => { const passwordInput = Selector('#password')
await t.typeText(passwordInput, 'password1234')})
With type text, the action takes two arguments: the first is the selector we want to type text into, and the second is the string that we would like to be entered.
Press Key
The press key action enables the test to press a key of your choice. This can be either a letter, a number, or anything on the keyboard!
test('name of your test here', async t => { await t.pressKey('enter')})
There’s only one argument for pressKey: the key you want to be pressed!
Hover
A hover actions tells the test to hover your mouse over a certain element. Perhaps you want a button to change colors when you hover over it:
test('name of your test here', async t => { const colorChangeButton = Selector('#color-change-button')
await t.hover(colorChangeButton)})
Like the click action, the only argument you need is the selector of the element you want to hover over.
Navigate
The navigateTo action is very helpful if you want to navigate to a new URL in the middle of a test:
test('name of your test here', async t => { await t.navigateTo('http://www.blairebaker.com')})
The URL you want to navigate to is the only parameter, so in the example above you would be navigating to my faaaaabulous website.
These are the ones that you are most likely to use, but there are plenty more. Read more about them in the super helpful TestCafe documentation. Happy coding!