All files / lib matcher.js

94.44% Statements 34/36
87.5% Branches 14/16
100% Functions 3/3
96.88% Lines 31/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83              1x 1x 1x                                 1x     24x   24x 22x 1x   21x 21x 2x 1x   1x   22x   22x 22x 59x 59x   22x 5x                   1x 3x 3x 17x 17x       15x 15x       3x 3x   1x 1x          
"use strict";
/**
 * Matchers.
 *
 * @module
 */
 
var _ = require("lodash");
var Assertion = require("chai").Assertion;
var U = require("glace-utils");
/**
 * Checks expectation corresponds to condition.
 *
 * @method
 * @arg {string} cond - conditions for assertion.
 * @arg {string} [msg] - message to throw in case of wrong conditions.
 * @example
 
 await $.checkBalance({ "to be not equal": 100 })
 
 Steps.prototype.checkBalance = async function (condition) {
    var currBalance = await this.getBalance();
 
    expect(currBalance).correspond(condition, "Invalid user balance");
};
 */
Assertion.prototype.correspond = function (cond, msg) {
    var matchers, expVal;
 
    if (msg) this.__flags.message = msg;
 
    if (typeof(cond) === "object") {
        if (Object.keys(cond).length !== 1) {
            throw new Error("Condition should contain only one key-value pair");
        }
        matchers = Object.keys(cond)[0];
        expVal = Object.values(cond)[0];
    } else if (typeof(cond) === "string") {
        matchers = cond;
    } else {
        throw new Error("Condition should be string or object only");
    }
    matchers = _.filter(_.split(matchers, " "));
 
    var predicate = this;
    for (var matcher of matchers) {
        predicate = predicate[matcher];
        Iif (!predicate) throw new TypeError(`Undefined matcher '${matcher}'`);
    }
    if (expVal) predicate.call(this, expVal);
    return this;
};
/**
 * Checks expectation corresponds to condition during timeout.
 * 
 * @arg {string|object} cond - Condition for assertion.
 * @arg {number} [timeout=1] - Timeout to wait for matching.
 * @arg {string} [msg] - Error message.
 * @throws {Error} If condition wasn't matched during timeout.
 */
Assertion.prototype.waitFor = async function (cond, timeout, msg) {
    var err = null;
    var predicate = async () => {
        try {
            return await new Assertion(
                await this.__flags.object(),
                this.__flags.message).correspond(cond, msg);
        } catch (e) {
            err = e;
            return false;
        }
    };
 
    var result = await U.waitFor(predicate, { timeout: timeout });
    if (result) return this;
 
    Eif (err) {
        throw err;
    } else {
        throw new Error("Unexpected matcher error");
    }
};