Skip to main content

prepareBrowser

Overview​

This parameter is a hook. The function specified for this parameter will be automatically called before running tests in the browser. The function receives a reference to the browser session as an argument.

The prepareBrowser hook is a perfect place to set up all of your custom commands or overwrite existing ones.

info

Read more about custom commands in our guide.

Usage Examples​

Adding new browser commands or overwriting existing browser commands​

This is how you can add or overwrite browser commands:

testplane.config.ts
import type { ConfigInput } from "testplane";
import { openScenario, customUrl } from "./testplane/browser-commands";
import { getCoords } from "./testplane/element-commands";

export default {
// ...
prepareBrowser: function (browser) {
// Browser commands
browser.addCommand("openScenario", openScenario);
// Element commands
browser.addCommand("getCoords", getCoords, true);
// Browser command overwrites
browser.overwriteCommand("url", customUrl);
},
} satisfies ConfigInput;

Adding a set of commands from a folder​

If the project has many specific commands, it is convenient to store them in a separate folder, and add all commands at once in a unified manner in prepareBrowser. For example:

testplane.config.ts
import type { ConfigInput } from "testplane";
import path from "path";
import glob from "fast-glob";

export default {
// ...
prepareBrowser: function (browser) {
const files = glob.sync(["tests/testplane/commands/*.(js|ts)", "!**/*.d.ts"]);

files.forEach(file => {
const module = require(path.resolve(process.cwd(), file));
const name = path.basename(file, path.extname(file));

browser.addCommand(name, typeof module === "object" ? module[name] : module);
});
},
};
tests/testplane/commands/myCheckCookie.js
export default async function (cookieName) {
const cookies = await this.getCookies(cookieName);

assert.isTrue(cookies[0], `cookie named ${cookieName} is not set`);
}

Here, the browser.getCookies command is used.