定義自訂斷言
總覽
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);
};
};