定义自定义断言
概述
Nightwatch 允许您甚至定义自己的断言,扩展可用的 .assert
和 .verify
命名空间。为此,请创建一个新文件夹(例如 nightwatch/assertions
)并在其中开始定义自己的断言,每个断言都在其自己的文件中。
然后在 nightwatch.json
文件中指定该文件夹的路径,作为 custom_assertions_path
属性。
nightwatch.json
{
"custom_assertions_path" : "nightwatch/assertions"
}
自定义断言也继承自 EventEmitter。要查看一些示例,请查看 Github 上的断言模块
/nightwatch/tree/main/lib/selenium/assertions
定义自定义断言
断言实现了一个简单的接口,该接口在内置断言和自定义断言之间共享
nightwatch/assertions/customAssert.js
exports.assertion = function(definition, expectedText, msg) {
// If the custom commands operates with DOM elements, this options should be set
// this.options = {
// elementSelector: true
// };
/**
* Returns the message format which will be used to output the message in the console and also
* the arguments which will be used for replace the place holders, used in the order of appearance
*
* The message format also takes into account whether the .not negate has been used
*
* @return undefined
*/
this.formatMessage = function() {
// Use this.negate to determine if ".not" is in use
// Example:
const message = `Testing if the page title ${this.negate ? 'doesn't equal %s' : 'equals %s'}`;
return {
message,
args: [`'${expected}'`]
}
};
/**
* Returns the expected value of the assertion which is displayed in the case of a failure
*
* @return {string}
*/
this.expected = function() {
return this.negate ? `is not '${expectedText}'` : `is '${expectedText}'`;
};
/**
* Given the value, the condition used to evaluate if the assertion is passed
* @param {*} value
* @return {Boolean}
*/
this.evaluate = function(value) {
if (typeof value != 'string') {
return false;
}
return value.includes(expectedText);
};
/**
* Called with the result object of the command to retrieve the value which is to be evaluated
*
* @param {Object} result
* @return {*}
*/
this.value = function(result) {
return result.value;
};
/**
* When defined, this method is called by the assertion runner with the command result, to determine if the
* value can be retrieved successfully from the result object
*
* @param result
* @return {boolean|*}
*/
this.failure = function(result) {
return result === false || result && result.status === -1;
};
/**
* When defined, this method is called by the assertion runner with the command result to determine the actual
* state of the assertion in the event of a failure
*
* @param {Boolean} passed
* @return {string}
*/
this.actual = function(passed) {
return passed ? `contains '${expectedText}'` : `does not contain '${expectedText}'`;
};
/**
* The command which is to be executed by the assertion runner; Nightwatch api is available as this.api
* @param {function} callback
*/
this.command = function(callback) {
// Example: this.api.getText(definition, callback);
setTimeout(function() {
// The object containing a "value" property will be passed to the .value() method to determine the value w
// which is to be evaluated (by the .evaluate() method)
callback({
value: ''
});
}, 1000);
};
};