You can easily reuse code in TestCafe using Page Object model/pattern.
The way I organise a TestCafe project in the project dir is the following:
.
├── config.json
├── Helpers
├── node_modules
├── Objects
├── package.json
├── package-lock.json
├── Resources
├── Results
└── Tests
In Objects/
, you can declare a class that represents something on your website. E.g. you can create a class with one action logIn
for a login page:
import { Selector, t } from 'testcafe';
class LogIn {
constructor () {
this.logInEmailInput = Selector('#LoginViewModel_Email');
this.logInPwdInput = Selector('#LoginViewModel_Password');
this.enterButton = Selector('button').withExactText('Sign In');
}
async logIn (email, pwd) {
await t
.typeText(this.logInEmailInput, email)
.typeText(this.logInPwdInput, pwd)
.click(this.enterButton);
}
}
export default new LogIn();
Then in Tests/
, I can test a user (multiple users) can actually log into the system:
import { Selector } from 'testcafe';
import config from '../config';
import LogIn from '../Objects/logIn';
import PageMsg from '../Objects/pageMsg';
const testData = require('../Resources/logIn.json');
fixture `Log In`
.page `${config.baseUrl}`;
testData.credentials.forEach(credentials => {
test('Log Into User Account', async t => {
// This is where I reuse code from the above-mentioned class
await LogIn.logIn(credentials.username, credentials.password);
// I assert that the action actually was successful
await t
.expect(PageMsg.pageMsg.innerText).eql(PageMsg.successfulLogIn);
});
});
If I want to test something inside a user profile, I'd need to log in first. For that, I can reuse LogIn.logIn()
method again, this time perhaps in before
or beforeEach
hook.
Another code that could be reused is in Helpers/
. TestCafe for example doesn't provide a function for reloading the current page, so I can create my own inside Helpers/
directory:
import { t } from 'testcafe';
export async function reload () {
await t
.eval(() => location.reload(true));
}
Then I'd use it in tests like so:
await reload();
In other test frameworks I've used in the past I knew how to call one test case from another (i.e. reusing code from one file in the other file).
Calling test cases from other test cases in my opinion creates more dependencies than you want to aim for. Better follow this Page Object model.
TestCafe provides a tutorial on how to structure tests, you can find more here: https://devexpress.github.io/testcafe/documentation/guides/basic-guides/organize-tests.html and here: https://devexpress.github.io/testcafe/documentation/guides/concepts/page-model.html The second link is a step-by-step tutorial on how to go about this PO model.