Code coverage report for lib/assertions.js

Statements: 98.56% (273 / 277)      Branches: 96.73% (148 / 153)      Functions: 100% (57 / 57)      Lines: 98.56% (273 / 277)      Ignored: none     

All files » lib/ » assertions.js
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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 4881 1 1 1 1   1 1 1   1 1 946     1 758 8   750       1 687     1 2     1 5     1 3     1 1     1 8     1 8 8 5   8 8   3               1 223   218           5     200       1 193 193     1 3 5 5     3 3 3       1 35     1 113 34 29   79             1 31 10 16   21   20 4 6     16 16 31 31 2   29       6 6 6 11 5   11 1     6 6       1         1 12 2     10     1 34 34 22 12 4 8 7   1     33     1 10     1 20       20 25   20 8 7   12       1 20 20   20 15 16   5 3 5   2 1   1         1 8     1 8     1 7 7 6     1 24     1 12     1 7     1 4     1 2     1 2     1 241 241   29 22 22       22       11     29       1 163 163 1       162 162   162 162   160 160 104 56     56     160 27 133 120 13 11 2 1   158     160 160     130   30       1 38 38 34 4 2 2 8     2   36 36 35 1   35   35 35 99 99   15       35 35 11 11 11 11 1   10   11 11 11   11 15 15 15 15         15 4             1 29 29 21 8 6 6 16     2   27 27 26 2   25 25     1 9 6 9   6 3         1 12 12 8 8 4 2 2 8     2   10 10 9 1   9   9 9 28 28   2       9 9 2 2         2 2 2 2 2         2               1 17   17 17 21 1     16 6 6 9   5 5 13   5        
var shim = require('./shim');
var forEach = shim.forEach;
var getKeys = shim.getKeys;
var every = shim.every;
var indexOf = shim.indexOf;
 
var utils = require('./utils');
var isRegExp = utils.isRegExp;
var isArray = utils.isArray;
 
module.exports = function (expect) {
    expect.addAssertion('[not] to be (ok|truthy)', function (expect, subject) {
        this.assert(subject);
    });
 
    expect.addAssertion('[not] to be', function (expect, subject, value) {
        if (typeof subject === 'string' && typeof value === 'string') {
            expect(subject, '[not] to equal', value);
        } else {
            expect(subject === value, '[not] to be truthy');
        }
    });
 
    expect.addAssertion('[not] to be true', function (expect, subject) {
        expect(subject, '[not] to be', true);
    });
 
    expect.addAssertion('[not] to be false', function (expect, subject) {
        expect(subject, '[not] to be', false);
    });
 
    expect.addAssertion('[not] to be falsy', function (expect, subject) {
        expect(subject, '[!not] to be truthy');
    });
 
    expect.addAssertion('[not] to be null', function (expect, subject) {
        expect(subject, '[not] to be', null);
    });
 
    expect.addAssertion('[not] to be undefined', function (expect, subject) {
        expect(typeof subject, '[not] to be', 'undefined');
    });
 
    expect.addAssertion('[not] to be NaN', function (expect, subject) {
        expect(isNaN(subject), '[not] to be true');
    });
 
    expect.addAssertion('[not] to be close to', function (expect, subject, value, epsilon) {
        this.errorMode = 'bubble';
        if (typeof epsilon !== 'number') {
            epsilon = 1e-9;
        }
        try {
            expect(Math.abs(subject - value), '[not] to be less than or equal to', epsilon);
        } catch (e) {
            expect.fail('expected {0} {1} {2} (epsilon: {3})',
                        expect.inspect(subject),
                        this.testDescription,
                        expect.inspect(value),
                        epsilon.toExponential());
        }
    });
 
    expect.addAssertion('[not] to be (a|an)', function (expect, subject, type) {
        if ('string' === typeof type) {
            // typeof with support for 'array'
            expect('array' === type ? isArray(subject) :
                    'object' === type ? 'object' === typeof subject && null !== subject :
                        /^reg(?:exp?|ular expression)$/.test(type) ? isRegExp(subject) :
                            type === typeof subject,
                   '[not] to be true');
        } else {
            expect(subject instanceof type, '[not] to be true');
        }
 
        return this;
    });
 
    // Alias for common '[not] to be (a|an)' assertions
    expect.addAssertion('[not] to be (a|an) (boolean|number|string|function|object|array|regexp|regex|regular expression)', function (expect, subject) {
        var matches = /(.* be (?:a|an)) ([\w\s]+)/.exec(this.testDescription);
        expect(subject, matches[1], matches[2]);
    });
 
    forEach(['string', 'array', 'object'], function (type) {
        expect.addAssertion('to be (the|an) empty ' + type, function (expect, subject) {
            expect(subject, 'to be a', type);
            expect(subject, 'to be empty');
        });
 
        expect.addAssertion('to be a non-empty ' + type, function (expect, subject) {
            expect(subject, 'to be a', type);
            expect(subject, 'not to be empty');
        });
    });
 
    expect.addAssertion('[not] to match', function (expect, subject, regexp) {
        expect(regexp.exec(subject), '[not] to be truthy');
    });
 
    expect.addAssertion('[not] to have [own] property', function (expect, subject, key, value) {
        if (arguments.length === 4) {
            expect(subject, 'to have [own] property', key);
            expect(subject[key], '[not] to equal', value);
        } else {
            expect(this.flags.own ?
                   subject && subject.hasOwnProperty(key) :
                   subject && subject[key] !== undefined,
                   '[not] to be truthy');
        }
    });
 
    expect.addAssertion('[not] to have [own] properties', function (expect, subject, properties) {
        if (properties && isArray(properties)) {
            forEach(properties, function (property) {
                expect(subject, '[not] to have [own] property', property);
            });
        } else if (properties && typeof properties === 'object') {
            // TODO the not flag does not make a lot of sense in this case
            if (this.flags.not) {
                forEach(getKeys(properties), function (property) {
                    expect(subject, 'not to have [own] property', property);
                });
            } else {
                try {
                    forEach(getKeys(properties), function (property) {
                        var value = properties[property];
                        if (typeof value === 'undefined') {
                            expect(subject, 'not to have [own] property', property);
                        } else {
                            expect(subject, 'to have [own] property', property, value);
                        }
                    });
                } catch (e) {
                    e.actual = expect.sanitize(subject);
                    e.expected = expect.sanitize(properties);
                    for (var propertyName in subject) {
                        if ((!this.flags.own || subject.hasOwnProperty(propertyName)) && !(propertyName in properties)) {
                            e.expected[propertyName] = expect.sanitize(subject[propertyName]);
                        }
                        if (!this.flags.own && !(propertyName in e.actual)) {
                            e.actual[propertyName] = expect.sanitize(subject[propertyName]);
                        }
                    }
                    e.showDiff = true;
                    throw e;
                }
            }
        } else {
            throw new Error("Assertion '" + this.testDescription + "' only supports " +
                            "input in the form of an Array or an Object.");
        }
    });
 
    expect.addAssertion('[not] to have length', function (expect, subject, length) {
        if (!subject || typeof subject.length !== 'number') {
            throw new Error("Assertion '" + this.testDescription +
                            "' only supports array like objects");
        }
        expect(subject.length, '[not] to be', length);
    });
 
    expect.addAssertion('[not] to be empty', function (expect, subject) {
        var length;
        if (subject && 'number' === typeof subject.length) {
            length = subject.length;
        } else if (isArray(subject) || typeof subject === 'string') {
            length = subject.length;
        } else if (subject && typeof subject === 'object') {
            length = getKeys(subject).length;
        } else {
            throw new Error("Assertion '" + this.testDescription +
                            "' only supports strings, arrays and objects");
        }
        expect(length, '[not] to be', 0);
    });
 
    expect.addAssertion('to be non-empty', function (expect, subject) {
        expect(subject, 'not to be empty');
    });
 
    expect.addAssertion('to [not] [only] have (key|keys)', '[not] to have (key|keys)', function (expect, subject, keys) {
        keys = isArray(keys) ?
            keys :
            Array.prototype.slice.call(arguments, 2);
 
        var hasKeys = subject && every(keys, function (key) {
            return subject.hasOwnProperty(key);
        });
        if (this.flags.only) {
            expect(hasKeys, 'to be truthy');
            expect(getKeys(subject).length === keys.length, '[not] to be truthy');
        } else {
            expect(hasKeys, '[not] to be truthy');
        }
    });
 
    expect.addAssertion('[not] to contain', function (expect, subject, arg) {
        var args = Array.prototype.slice.call(arguments, 2);
        var that = this;
 
        if ('string' === typeof subject) {
            forEach(args, function (arg) {
                expect(subject.indexOf(arg) !== -1, '[not] to be truthy');
            });
        } else if (isArray(subject)) {
            forEach(args, function (arg) {
                expect(subject && indexOf(subject, arg) !== -1, '[not] to be truthy');
            });
        } else if (subject === null) {
            expect(that.flags.not, '[not] to be falsy');
        } else {
            throw new Error("Assertion '" + this.testDescription +
                            "' only supports strings and arrays");
        }
    });
 
    expect.addAssertion('[not] to be finite', function (expect, subject) {
        expect(typeof subject === 'number' && isFinite(subject), '[not] to be truthy');
    });
 
    expect.addAssertion('[not] to be infinite', function (expect, subject) {
        expect(typeof subject === 'number' && !isNaN(subject) && !isFinite(subject), '[not] to be truthy');
    });
 
    expect.addAssertion('[not] to be within', function (expect, subject, start, finish) {
        this.args = [start + '..' + finish];
        expect(subject, 'to be a number');
        expect(subject >= start && subject <= finish, '[not] to be true');
    });
 
    expect.addAssertion('<', '[not] to be (<|less than|below)', function (expect, subject, value) {
        expect(subject < value, '[not] to be true');
    });
 
    expect.addAssertion('<=', '[not] to be (<=|less than or equal to)', function (expect, subject, value) {
        expect(subject <= value, '[not] to be true');
    });
 
    expect.addAssertion('>', '[not] to be (>|greater than|above)', function (expect, subject, value) {
        expect(subject > value, '[not] to be true');
    });
 
    expect.addAssertion('>=', '[not] to be (>=|greater than or equal to)', function (expect, subject, value) {
        expect(subject >= value, '[not] to be true');
    });
 
    expect.addAssertion('[not] to be positive', function (expect, subject) {
        expect(subject, '[not] to be >', 0);
    });
 
    expect.addAssertion('[not] to be negative', function (expect, subject) {
        expect(subject, '[not] to be <', 0);
    });
 
    expect.addAssertion('[not] to equal', function (expect, subject, value) {
        try {
            expect(expect.equal(value, subject), '[not] to be true');
        } catch (e) {
            if (!this.flags.not) {
                e.expected = expect.sanitize(value);
                e.actual = expect.sanitize(subject);
                // Explicitly tell mocha to stringify and diff arrays
                // and objects, but only when the types are identical
                // and non-primitive:
                if (e.actual && e.expected &&
                    typeof e.actual === 'object' &&
                    typeof e.expected === 'object' &&
                    isArray(e.actual) === isArray(e.expected)) {
                    e.showDiff = true;
                }
            }
            throw e;
        }
    });
 
    expect.addAssertion('[not] to (throw|throw error|throw exception)', function (expect, subject, arg) {
        this.errorMode = 'nested';
        if (typeof subject !== 'function') {
            throw new Error("Assertion '" + this.testDescription +
                            "' only supports functions");
        }
 
        var thrown = false;
        var argType = typeof arg;
 
        try {
            subject();
        } catch (e) {
            var subject;
            if (e._isUnexpected) {
                subject = e.output.toString();
            } else Iif (typeof e === 'string') {
                subject = e;
            } else {
                subject = e.message;
            }
 
            if ('function' === argType) {
                arg(e);
            } else if ('string' === argType) {
                expect(subject, '[not] to equal', arg);
            } else if (isRegExp(arg)) {
                expect(subject, '[not] to match', arg);
            } else if (this.flags.not) {
                expect.fail('threw: {0}', e._isUnexpected ? e.output : subject);
            }
            thrown = true;
        }
 
        this.errorMode = 'default';
        if ('string' === argType || isRegExp(arg)) {
            // in the presence of a matcher, ensure the `not` only applies to
            // the matching.
            expect(thrown, 'to be true');
        } else {
            expect(thrown, '[not] to be true');
        }
    });
 
    expect.addAssertion('to be (a|an) [non-empty] (map|hash|object) whose values satisfy', function (expect, subject, callbackOrString) {
        var callback;
        if ('function' === typeof callbackOrString) {
            callback = callbackOrString;
        } else if ('string' === typeof callbackOrString) {
            var args = Array.prototype.slice.call(arguments, 2);
            callback = function (value) {
                expect.apply(expect, [value].concat(args));
            };
        } else {
            throw new Error('Assertion "' + this.testDescription + '" expects a function as argument');
        }
        this.errorMode = 'nested';
        expect(subject, 'to be an object');
        if (this.flags['non-empty']) {
            expect(subject, 'to be non-empty');
        }
        this.errorMode = 'bubble';
 
        var errors = {};
        forEach(getKeys(subject), function (key, index) {
            try {
                callback(subject[key], index);
            } catch (e) {
                errors[key] = e;
            }
        });
 
        var errorKeys = getKeys(errors);
        if (errorKeys.length > 0) {
            expect.fail(function (output) {
                var subjectOutput = expect.inspect(subject);
                output.error('failed expectation in');
                if (subjectOutput.size().height > 1) {
                    output.nl();
                } else {
                    output.sp();
                }
                subjectOutput.error(':');
                output.block(subjectOutput).nl();
                output.indentLines();
 
                forEach(errorKeys, function (key, index) {
                    var error = errors[key];
                    output.i().text(key).text(': ');
                    Eif (error._isUnexpected) {
                        output.block(error.output);
                    } else {
                        output.block(output.clone().text(error.message));
                    }
 
                    if (index < errorKeys.length - 1) {
                        output.nl();
                    }
                });
            });
        }
    });
 
    expect.addAssertion('to be (a|an) [non-empty] array whose items satisfy', function (expect, subject, callbackOrString) {
        var callback;
        if ('function' === typeof callbackOrString) {
            callback = callbackOrString;
        } else if ('string' === typeof callbackOrString) {
            var args = Array.prototype.slice.call(arguments, 2);
            callback = function (item) {
                expect.apply(expect, [item].concat(args));
            };
        } else {
            throw new Error('Assertion "' + this.testDescription + '" expects a function as argument');
        }
        this.errorMode = 'nested';
        expect(subject, 'to be an array');
        if (this.flags['non-empty']) {
            expect(subject, 'to be non-empty');
        }
        this.errorMode = 'bubble';
        expect(subject, 'to be a map whose values satisfy', callback);
    });
 
    forEach(['string', 'number', 'boolean', 'array', 'object', 'function', 'regexp', 'regex', 'regular expression'], function (type) {
        expect.addAssertion('to be (a|an) [non-empty] array of ' + type + 's', function (expect, subject) {
            expect(subject, 'to be an array whose items satisfy', function (item) {
                expect(item, 'to be a', type);
            });
            if (this.flags['non-empty']) {
                expect(subject, 'to be non-empty');
            }
        });
    });
 
    expect.addAssertion('to be (a|an) [non-empty] (map|hash|object) whose keys satisfy', function (expect, subject, callbackOrString) {
        var callback;
        if ('function' === typeof callbackOrString) {
            this.errorMode = 'nested';
            callback = callbackOrString;
        } else if ('string' === typeof callbackOrString) {
            var args = Array.prototype.slice.call(arguments, 2);
            callback = function (key) {
                expect.apply(expect, [key].concat(args));
            };
        } else {
            throw new Error('Assertion "' + this.testDescription + '" expects a function as argument');
        }
        this.errorMode = 'nested';
        expect(subject, 'to be an object');
        if (this.flags['non-empty']) {
            expect(subject, 'to be non-empty');
        }
        this.errorMode = 'bubble';
 
        var errors = {};
        forEach(getKeys(subject), function (key, index) {
            try {
                callback(key);
            } catch (e) {
                errors[key] = e;
            }
        });
 
        var errorKeys = getKeys(errors);
        if (errorKeys.length > 0) {
            expect.fail(function (output) {
                output.error('failed expectation on keys ')
                      .text(getKeys(subject).join(', '))
                      .error(':').nl()
                      .indentLines();
 
                forEach(errorKeys, function (key, index) {
                    var error = errors[key];
                    output.i().text(key).text(': ');
                    Eif (error._isUnexpected) {
                        output.block(error.output);
                    } else {
                        output.block(output.clone().text(error.message));
                    }
 
                    Iif (index < errorKeys.length - 1) {
                        output.nl();
                    }
                });
            });
        }
    });
 
    expect.addAssertion('to be canonical', function (expect, subject, stack) {
        stack = stack || [];
 
        var i;
        for (i = 0 ; i < stack.length ; i += 1) {
            if (stack[i] === subject) {
                return;
            }
        }
        if (subject && typeof subject === 'object') {
            var keys = getKeys(subject);
            for (i = 0 ; i < keys.length - 1 ; i += 1) {
                expect(keys[i], 'to be less than', keys[i + 1]);
            }
            stack.push(subject);
            forEach(keys, function (key) {
                expect(subject[key], 'to be canonical', stack);
            });
            stack.pop(subject);
        }
    });
};