Nightwatch.js 使用 getCookie 等客户端命令编写断言

Nightwatch.js writing assertions with client commands like getCookie

我正在尝试在 Nightwatch.js 中编写一个使用现有客户端命令的自定义命令,然后将其传递给断言。但是,它没有向断言传递任何值。我认为这可能与这里的这句话有关: https://nightwatchjs.org/guide/extending-nightwatch/#writing-custom-commands

The command module needs to export a command function, which needs to call at least one Nightwatch api method (such as .execute()). This is due to a limitation of how the asynchronous queueing system of commands works. You can also wrap everything in a .perform() call.

我试过按照它的建议将它包装在 perform() 调用中,但它没有用,也许我做错了什么。我尽可能地简化了它,因此它应该始终将 true 传递给断言。

isMyCookiePresent.js:

module.exports.command = function (callback) {
    let self = this;

    this.getCookies(function(res) {
        if (typeof callback === "function") {
            callback.call(self, true);
        }
    });

    return this;
};

myCookiePresent.js:

exports.assertion = function(msg) {
    this.formatMessage = function() {
        const message = msg || `Checking if my cookie is present`;

        return {
            message,
            args: []
        }
    };

    this.expected = function() {
        return this.negate ? `false` : `true`;
    };

    this.evaluate = function(value) {
        return value === true;
    };

    this.value = function(result = {}) {
        return result.value || false;
    };

    this.command = function(callback) {
        this.api.isMyCookiePresent(callback);
    };
};

这个问题原来是我的一个简单遗漏:对于像 execute 这样的大多数命令,Nightwatch returns 是一个格式良好的对象,其中包含一个值。但是,仅仅通过回调发送文字值并不能做到这一点。

因此,最好给断言发送一个对象,带一个value字段,如:

callback.call(self, true);

应该变成:

const result = {
    value: true
};
callback.call(self, result);

注:在某些情况下,前面的断言中的值是可能的,例如:

this.value = function(result = {}) {
    return result.value || false;
};

=>

this.value = function(result = {}) {
    return result || false;
};

但是,在这种情况下,当参数为 false 时,它会破坏否定断言(当它期望参数为假时)。