Working with TestCafe
- Can my tests reference third-party libraries?
- Can I store TestCafe settings in a configuration file?
- How do I access environment variables?
- How do I reference elements with dynamic IDs?
- How do I respond to geolocation prompts?
- How do I detect the version number of the TestCafe framework?
- I installed TestCafe but I cannot run it. What should I do?
- My TestCafe test yields an unexpected error. What can cause that?
- I installed TestCafe plugins but they do not work. What have I done wrong?
- My tests fail because TestCafe cannot locate a page element. Why does this happen?
- My tests fail because TestCafe cannot resolve a network request. What are the possible reasons?
- TestCafe cannot open the page because the browser cannot establish a secure connection. What should I do?
- My tests fail in native automation mode because the website uses an invalid SSL certificate. What should I do?
Can my tests reference third-party libraries?
Yes — both on the server side and the client side.
Server side
TestCafe tests are Node.js scripts that can incorporate other Node libraries. Add an import
statement to import a module.
import fs from 'fs';
fixture `fixture`
.page('http://localhost/testcafe/');
test('test', async t => {
const filePath = 'filepath.js';
await t.expect(fs.existsSync(filePath)).ok();
});
Client side
TestCafe can inject front-end JavaScript libraries into your web application. See Inject Client Scripts for more information.
fixture `My fixture`
.page `https://example.com`
// The fixture.clientScripts method injects jquery.js
// into all pages visited in this fixture.
.clientScripts('scripts/jquery.js');
test('test', async t => {
const clientFunction = ClientFunction(() => {
// You can use $ here
return $('div').text();
});
const text = await clientFunction();
});
Can I store TestCafe settings in a configuration file?
You can store your TestCafe settings in a dedicated configuration file. TestCafe supports two configuration file formats — JSON and JavaScript.
On startup, TestCafe looks for a configuration file (.testcaferc.js
, .testcaferc.cjs
, or .testcaferc.json
) in the current working directory. You can specify a non-standard configuration file path with the --config-file
command line option.
Read the configuration file guide for more information.
How do I access environment variables?
The TestCafe configuration file can reference environment variables. Read the Access Environment Variables in Tests recipe for more information.
How do I reference elements with dynamic IDs?
Many JavaScript frameworks generate dynamic IDs for page elements. Selector queries that reference these dynamic IDs are likely to fail.
To identify elements with a dynamic id
attribute, create Selectors based on the element’s class, content, tag name, or position.
See the Select Elements With Dynamic IDs example for details.
How do I respond to geolocation prompts?
Set a Native Dialog Handler to handle geolocation prompts.
To detect geolocation requests, pass the type
argument to the handler function.
- Return an
Error
type object to Block geolocation requests. - Return an object with coordinates to trigger the
success
callback of the getCurrentPosition method.
Example:
// Test
test('Switch from "allow" to "block"', async t => {
await t
.setNativeDialogHandler((type) => {
if (type === 'geolocation')
return { timestamp: 12356, accuracy: 20, coords: {latitude: '34.15321262322903', longitude: '-118.25543996370723'}; // Passes this data to the geolocation request
return null;
});
.click('#buttonGeo')
.setNativeDialogHandler((type) => {
if (type !== 'geolocation')
return null;
const err = new Error('Some error');
err.code = 1;
return err; // Blocks the geolocation request
})
.click('#buttonGeo');
How do I detect the version number of the TestCafe framework?
The -v (--version)
CLI option outputs the version number to the console:
To access TestCafe version number in test code, import the version
constant from the testcafe
module:
import {version} from 'testcafe';
console.log(`TestCafe version: ${version}`);
To access the framework’s version number in your custom reporter, reference the first argument (version
) of the init
method:
init (version) {
this
.write(`Using TestCafe ${version}`)
.newline()
}
I installed TestCafe but I cannot run it. What should I do?
Check your firewall settings. Make sure that your firewall does not block the framework’s network activity. TestCafe communicates with the network over two different ports in the [0 - 65535] range. The framework selects two unoccupied network ports on launch. But you can specify port numbers yourself.
Create a firewall rule that keeps two ports in the [0 - 65535] range open. Specify these ports with the --ports command line option or the createTestCafe Test Runner function when you launch the framework.
Specify proxy server settings. If the machine that runs tests needs a proxy to access the internet, specify proxy settings when you launch TestCafe. Use the --proxy command line option or the useProxy API method.
Check X11 (Linux users only). TestCafe relies on X11 to launch most Linux browsers. If you use the Xvbf window server, you can only run browsers in headless mode. If your setup doesn’t include X11 or Xvbf, you can only run tests on cloud farms and in headless Google Chrome.
My TestCafe test yields an unexpected error. What can cause that?
JavaScript errors. TestCafe tests fail when a page yields a JavaScript error. Check your browser’s console for error messages. Fix the errors or request TestCafe to ignore JavaScript errors during test runs.
Browser extensions. Browser extensions may interfere with test execution. That’s why TestCafe launches browsers with an empty user profile. If you enabled the userProfile option earlier, disable it.
Third-party modules. In rare cases, third-party modules can interfere with test execution. If your current TestCafe installation is local, install the framework globally and launch the test from a directory that doesn’t contain third-party Node modules.
I installed TestCafe plugins but they do not work. What have I done wrong?
Local TestCafe installations only detect local TestCafe plugins. If your current TestCafe installation is local, install the plugin locally:
npm install --save-dev {pluginName}
If your current TestCafe installation is global, install the plugin globally:
npm install -g {pluginName}
My tests fail because TestCafe cannot locate a page element. Why does this happen?
TestCafe uses Selector queries to locate page elements. Follow the steps below to diagnose Selector failure:
- View the test report. Locate the Selector query that failed.
- Insert the t.debug() action before the failing Selector declaration. The
t.debug
method pauses the test for troubleshooting purposes. - Run the test and wait until TestCafe stops test execution at the breakpoint.
- Inspect the action target with the browser’s development tools to ensure that it meets the interaction requirements.
The following tips and tricks may also help:
- Some web applications hide page elements when the window’s dimensions are too small. Run the test in full screen mode to resolve the issue. Adjust window size with the t.maximizeWindow and t.resizeWindow methods.
- Update TestCafe to the latest version. You may have encountered a bug that has already been fixed.
My tests fail because TestCafe cannot resolve a network request. What are the possible reasons?
If the TestCafe proxy does not receive the webpage within two minutes, TestCafe throws the following exception:
Failed to load the page at https://www.example.com.
Increase the value of the "pageRequestTimeout" variable,
enable the "retryTestPages" option, or use quarantine mode
to perform additional attempts to execute this test.
If you believe that this error is unwarranted, enable quarantine mode. The quarantine mode option forces TestCafe to repeat tests that fail until they yield conclusive results.
If the error persists, continue your investigation. Here are some of the reasons that this error may occur:
The Web server is not responding
Confirm the successful resolution of the website’s domain name. Check if the web application is online and able to receive incoming requests.
If the server is unstable, and you cannot fix it, enable one of the following options to retry failed page requests:
- ‘--retry-test-pages’ (CLI)
- ‘retryTestPages’ (configuration file)
- ‘retryTestPages’ option (TestCafe Runner)
Unstable or improperly configured network connection
Your network configuration may cause issues with server connection.
- Check your network settings.
- Check the stability of your network equipment.
- Check your proxy settings, or try a different proxy server.
- Use a VPN.
- Connect to a different network.
Lack of container or CI resources
Your browser may be unable to access the page because it lacks necessary system ressources.
If you run TestCafe in a container or on a CI server, use the following steps to diagnose the resource shortage:
- Increase the container’s resource limits.
- Set the concurrency factor to
1
. - Deploy the application’s Web server on a separate machine.
- Run tests on a local device outside a container.
If one of these solutions fixes your tests, assign more resources to the TestCafe framework.
- Adjust the container’s or environment’s settings to allocate more resources.
- If you use a cloud-based CI system, ask the service provider for an upgrade, or consider a different CI provider with better hardware and lower loads.
According to user feedback, the following CI systems work best with TestCafe:
TestCafe cannot open the page because the browser cannot establish a secure connection. What should I do?
If your computer belongs to multiple networks (for example, if you use a VPN), TestCafe may incorrectly detect the host IP. As a result, the browser can display the following error message:
<browsername> cannot open the page because <browsername> is unable to establish a secure connection to the server.
To fix the issue, launch TestCafe with the --hostname localhost
CLI option:
testcafe chrome test.js --hostname localhost
My tests fail in native automation mode because the website uses an invalid SSL certificate. What should I do?
When you use native automation, the browser displays a warning screen when it encounters an invalid SSL certificate. Launch the browser with the --ignore-certificate-errors
flag to disable this behavior:
testcafe 'chrome --ignore-certificate-errors' test.js