Giter Club home page Giter Club logo

power-assert's Introduction

power-assert

Power Assert in JavaScript. Provides descriptive assertion messages through standard assert interface. No API is the best API.

Build Status NPM package Bower package License

DESCRIPTION

What is power-assert?

power-assert provides descriptive assertion messages for your tests, like this.

  1) Array #indexOf() should return index when the value is present:
     AssertionError: # path/to/test/mocha_node.js:10

  assert(ary.indexOf(zero) === two)
         |   |       |     |   |
         |   |       |     |   2
         |   -1      0     false
         [1,2,3]

  [number] two
  => 2
  [number] ary.indexOf(zero)
  => -1

API

power-assert enhances these assert functions by espower. Produces descriptive message when assertion is failed.

power-assert is fully compatible with assert. So functions below are also available though they are not enhanced (does not produce descriptive message).

Since version 1.5.0, power-assert supports "strict mode" as well.

power-assert provides an API for customization.

  • assert.customize(options)

No API is the best API

Though power-assert is fully compatible with standard assert interface, all you need to remember is just an assert(any_expression) function in most cases.

The core value of power-assert is absolute simplicity and stability. Especially, power-assert sticks to the simplest form of testing, assert(any_expression).

    assert(types[index].name === bob.name)
           |    ||      |    |   |   |
           |    ||      |    |   |   "bob"
           |    ||      |    |   Person{name:"bob",age:5}
           |    ||      |    false
           |    |11     "alice"
           |    Person{name:"alice",age:3}
           ["string",98.6,true,false,null,undefined,#Array#,#Object#,NaN,Infinity,/^not/,#Person#]
  
    --- [string] bob.name
    +++ [string] types[index].name
    @@ -1,3 +1,5 @@
    -bob
    +alice

FAQ

INSTALL

npm install --save-dev power-assert <one of instrumentors>

or

bower install --save-dev power-assert
npm install --save-dev <one of instrumentors>

see list of instrumentors

CHANGELOG

See CHANGELOG

EXAMPLE

See HOW TO USE section for more details.

Note: There is an online demo site available.

Target test code (using Mocha in this example)

'use strict';

const assert = require('assert');

describe('Array', function(){
    let ary;
    beforeEach(() => {
        ary = [1,2,3];
    });
    describe('#indexOf()', () => {
        it('should return index when the value is present', () => {
            const zero = 0, two = 2;
            assert(ary.indexOf(zero) === two);
        });
        it('should return -1 when the value is not present', () => {
            const minusOne = -1, two = 2;
            assert.ok(ary.indexOf(two) === minusOne, 'THIS IS AN ASSERTION MESSAGE');
        });
    });
});

describe('various types', () => {
    let types;
    class Person {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
    }
    beforeEach(() => {
        types = [
            'string', 98.6, true, false, null, undefined,
            ['nested', 'array'],
            {object: true},
            NaN, Infinity,
            /^not/,
            new Person('alice', 3)
        ];
    });
    it('demo', () => {
        const index = types.length -1,
            bob = new Person('bob', 5);
        assert(types[index].name === bob.name);
    });
});

Be sure to transform test code

To use power-assert, you need to transform your test code for power-assert output.

Code transform is done by instrumentors below:

If you are using Node.js only, the easiest way is to use intelli-espower-loader. Steps are as follows.

Setup

npm install --save-dev mocha power-assert intelli-espower-loader

Run

Put tests into test directory then run. You will see the power-assert output appears.

  $ $(npm bin)/mocha --require intelli-espower-loader path/to/test/mocha_node.js


  Array
    #indexOf()
      1) should return index when the value is present
      2) should return -1 when the value is not present

  various types
    3) demo


  0 passing (43ms)
  3 failing

  1) Array #indexOf() should return index when the value is present:

      AssertionError:   # test/example2.js:13

  assert(ary.indexOf(zero) === two)
         |   |       |     |   |
         |   |       |     |   2
         |   -1      0     false
         [1,2,3]

  [number] two
  => 2
  [number] ary.indexOf(zero)
  => -1

      + expected - actual

      -false
      +true

      at Context.it (test/example2.js:13:13)

  2) Array #indexOf() should return -1 when the value is not present:

      AssertionError: THIS IS AN ASSERTION MESSAGE   # test/example2.js:17

  assert.ok(ary.indexOf(two) === minusOne, 'THIS IS AN ASSERTION MESSAGE')
            |   |       |    |   |
            |   |       |    |   -1
            |   1       2    false
            [1,2,3]

  [number] minusOne
  => -1
  [number] ary.indexOf(two)
  => 1

      + expected - actual

      -false
      +true

      at Context.it (test/example2.js:17:20)

  3) various types demo:

      AssertionError:   # test/example2.js:43

  assert(types[index].name === bob.name)
         |    ||      |    |   |   |
         |    ||      |    |   |   "bob"
         |    ||      |    |   Person{name:"bob",age:5}
         |    ||      |    false
         |    |11     "alice"
         |    Person{name:"alice",age:3}
         ["string",98.6,true,false,null,undefined,#Array#,#Object#,NaN,Infinity,/^not/,#Person#]

  --- [string] bob.name
  +++ [string] types[index].name
  @@ -1,3 +1,5 @@
  -bob
  +alice


      + expected - actual

      -false
      +true

      at Context.it (test/example2.js:43:9)

SEED PROJECTS

Some seed projects are available to help you start with power-assert.

module env tech stack
power-assert-node-seed Node.js power-assert + intelli-espower-loader
power-assert-testem-seed Browsers(by testem) power-assert + gulp-espower + testem.
power-assert-karma-seed Browsers(by Karma) power-assert + espowerify + browserify + Karma.

HOW TO USE

There are some ways to use power-assert. (If you want to see running examples, see SEED PROJECTS)

  1. power-assert + Babel + babel-preset-power-assert: The only way to enable power-assert if you are using Babel6+.
  2. power-assert + espower-loader or intelli-espower-loader : Simple and recommended (but only works under Node).
  3. power-assert + espower-coffee or espower-typescript: Use power-assert with AltJS. Recommended but only works under Node.
  4. power-assert + browserify + espowerify: if you are using browserify but not with Babel.
  5. power-assert + webpack + webpack-espower-loader: if you are using webpack but not with Babel.
  6. power-assert + espower-cli or grunt-espower or gulp-espower : Generate instrumented code so works anywhere.

using babel-preset-power-assert or babel-plugin-espower

If you are writing your code with Babel, you can instrument Power Assert feature with Babel and babel-preset-power-assert (or babel-plugin-espower).

see babel-plugin-espower README and babel-preset-power-assert README

using espower-loader or intelli-espower-loader

If you are writing Node.js app/module, you can instrument Power Assert feature without code generation by using espower-loader.

see espower-loader README.

FYI: You may be interested in intelli-espower-loader to go one step further. With intelli-espower-loader, you don't need to create loader file (like enable-power-assert.js). Just define test directory in package.json wow!

using espower-typescript

If you are writing Node.js app/module in TypeScript, you can instrument Power Assert feature without code generation by using espower-typescript.

see espower-typescript README.

using espower-coffee

If you are writing Node.js app/module in CoffeeScript, you can instrument Power Assert feature without code generation by using espower-coffee.

see espower-coffee README.

using espowerify

If you are using browserify but not with Babel, you can instrument Power Assert feature via espowerify.

see espowerify README.

using webpack-espower-loader

If you are using webpack but not with Babel, you can instrument Power Assert feature via webpack-espower-loader.

see webpack-espower-loader README.

using espower-cli

If you don't want to use grunt, gulp, browserify, and so on, you can use power-assert via bower, with generated code by espower-cli

see espower-cli README.

using gulp-espower

On the browser side and you are not using browserify but bower and gulp, you can use power-assert via bower, with generated code by gulp-espower

see gulp-espower README.

using grunt-espower

On the browser side and you are not using browserify but bower and Grunt, you can use power-assert via bower, with generated code by grunt-espower

see grunt-espower README.

CUSTOMIZATION API

power-assert provides an API for customization.

var assert = assert.customize(options)

Through this API, you can customize power-assert by changing some options.

var assert = require('power-assert').customize({
    output: {
        maxDepth: 2
    }
});

options

options has two top-level keys. assertion and output.

options.assertion

customization options for empower module. See empower API documentation for details. Note that some default values are different from empower's (modifyMessageOnRethrow: true and saveContextOnRethrow: true).

options.output

customization options for power-assert-formatter module. See power-assert-formatter API documentation for details.

default values

customizable properties and their default values are as follows.

var assert = require('power-assert').customize({
    assertion: {
        destructive: false,
        modifyMessageOnRethrow: true,
        saveContextOnRethrow: true,
        patterns: [
            'assert(value, [message])',
            'assert.ok(value, [message])',
            'assert.equal(actual, expected, [message])',
            'assert.notEqual(actual, expected, [message])',
            'assert.strictEqual(actual, expected, [message])',
            'assert.notStrictEqual(actual, expected, [message])',
            'assert.deepEqual(actual, expected, [message])',
            'assert.notDeepEqual(actual, expected, [message])',
            'assert.deepStrictEqual(actual, expected, [message])',
            'assert.notDeepStrictEqual(actual, expected, [message])'
        ]
    },
    output: {
        lineDiffThreshold: 5,
        maxDepth: 1,
        anonymous: 'Object',
        circular: '#@Circular#',
        lineSeparator: '\n',
        ambiguousEastAsianCharWidth: 2,
        widthOf: (Function to calculate width of string. Please see power-assert-formatter's documentation)
        stringify: (Function to stringify any target value. Please see power-assert-formatter's documentation)
        diff: (Function to create diff string between two strings. Please see power-assert-formatter's documentation)
        writerClass: (Constructor Function for output writer class. Please see power-assert-formatter's documentation)
        renderers: [
            './built-in/file',
            './built-in/assertion',
            './built-in/diagram',
            './built-in/binary-expression'
        ]
    }
});

INTERNAL DESIGN

power-assert family provides 1 main module, 4 core modules and many more instrumentors.

Main (facade) module is,

module description
power-assert Standard assert function on top of empower and power-assert-formatter

core modules are,

module description
empower Power Assert feature enhancer for assert function/object.
power-assert-formatter Power Assert output formatter.
espower Power Assert feature instrumentor core based on the ECMAScript AST defined in The ESTree Spec (formerly known as Mozilla SpiderMonkey Parser API).
espower-source Power Assert instrumentor from source to source, with source-map. (Thin wrapper of espower).

and instrumentors are,

module description
espower-loader Node module loader to apply espower on the fly.
intelli-espower-loader configure espower-loader with ease.
babel-preset-power-assert Babel preset to instrument power-assert feature into target files.
babel-plugin-espower Babel plugin to instrument power-assert feature into target files.
espowerify Browserify transform to apply espower to target files.
webpack-espower-loader Power Assert instrumentor module for webpack.
espower-cli Command line tool for power-assert.
grunt-espower Grunt task to apply espower to target files.
gulp-espower Gulp plugin to apply espower to target files.
karma-espower-preprocessor karma-preprocessor for power-assert.
espower-coffee power-assert instrumentor for CoffeeScript.
espower-typescript power-assert instrumentor for TypeScript.
espower-traceur power-assert instrumentor for ES6 using Traceur Compiler.
espower-babel [DEPRECATED] power-assert instrumentor for ES6 using Babel.

power-assert provides standard assert compatible function with Power Assert feature. (Best fit with Mocha. If you use assert-like objects provided by various testing frameworks such as QUnit or nodeunit. Please use empower and power-assert-formatter modules directly).

Internally, power-assert uses empower module to enhance power assert feature into the standard assert module, to run with the power assert feature added code by espower module, and prettify output using power-assert-formatter.

See power-assert-demo project for power-assert Demo running with mocha.

SUPPORTED FRAMEWORKS

FRAMEWORKS KNOWN TO WORK

OUR SUPPORT POLICY

For the Transpiler side, we support Node under maintenance. In other words, we stop supporting old Node version when their maintenance ends.

For the Runtime side, we support Node under maintenance and "modern enough" browsers such as Chrome, Firefox, Safari, Edge etc.

Any other environments are not supported officially (means that we do not test against them on CI service). power-assert is known to work with old browsers, and trying to keep them working though.

AUTHOR

CONTRIBUTORS

LICENSE

Licensed under the MIT license.

MORE OUTPUT EXAMPLES

Target test code (using QUnit in this example)

var q = require('qunitjs');

(function () {
    var empower = require('empower'),
        formatter = require('power-assert-formatter'),
        qunitTap = require("qunit-tap");
    empower(q.assert, formatter(), {destructive: true});
    qunitTap(q, require('util').puts, {showSourceOnFailure: false});
    q.config.autorun = false;
})();

q.test('spike', function (assert) {
    assert.ok(true);

    var hoge = 'foo';
    var fuga = 'bar';
    assert.ok(hoge === fuga, 'comment');

    var piyo = 3;
    assert.ok(fuga === piyo);

    var longString = 'very very loooooooooooooooooooooooooooooooooooooooooooooooooooong message';
    var anotherLongString = 'yet another loooooooooooooooooooooooooooooooooooooooooooooooooooong message';
    assert.ok(longString === anotherLongString);

    assert.ok(4 === piyo);

    assert.ok(4 !== 4);

    var falsyStr = '';
    assert.ok(falsyStr);

    var falsyNum = 0;
    assert.ok(falsyNum);

    var ary1 = ['foo', 'bar'];
    var ary2 = ['aaa', 'bbb', 'ccc'];
    assert.ok(ary1.length === ary2.length);
    assert.deepEqual(ary1, ary2);

    var actual = 16;
    assert.ok(5 < actual && actual < 13);

    actual = 4;
    assert.ok(5 < actual && actual < 13);

    actual = 10;
    assert.ok(actual < 5 || 13 < actual);


    var propName = 'bar',
        foo = {
            bar: {
                baz: false
            }
        };

    assert.ok(foo.bar.baz);
    assert.ok(foo['bar'].baz);
    assert.ok(foo[propName]['baz']);


    var truth = true;
    assert.ok(!truth);


    var func = function () { return false; };
    assert.ok(func());


    var obj = {
        age: function () {
            return 0;
        }
    };
    assert.ok(obj.age());


    var isFalsy = function (arg) {
        return !(arg);
    };
    var positiveInt = 50;
    assert.ok(isFalsy(positiveInt));


    var sum = function () {
        var result = 0;
        for (var i = 0; i < arguments.length; i += 1) {
            result += arguments[i];
        }
        return result;
    };
    var one = 1, two = 2, three = 3, seven = 7, ten = 10;
    assert.ok(sum(one, two, three) === seven);
    assert.ok(sum(sum(one, two), three) === sum(sum(two, three), seven));
    assert.ok((three * (seven * ten)) === three);


    var math = {
        calc: {
            sum: function () {
                var result = 0;
                for (var i = 0; i < arguments.length; i += 1) {
                    result += arguments[i];
                }
                return result;
            }
        }
    };
    assert.ok(math.calc.sum(one, two, three) === seven);
});

q.load();

espower code above then running under Node.js

# module: undefined
# test: spike
ok 1 - okay
not ok 2 - comment # path/to/examples/qunit_node.js:17
#
# assert.ok(hoge === fuga, 'comment')
#           |    |   |
#           |    |   "bar"
#           |    false
#           "foo"
#
# --- [string] fuga
# +++ [string] hoge
# @@ -1,3 +1,3 @@
# -bar
# +foo
#
# , test: spike
not ok 3 - # path/to/examples/qunit_node.js:20
#
# assert.ok(fuga === piyo)
#           |    |   |
#           |    |   3
#           |    false
#           "bar"
#
# [number] piyo
# => 3
# [string] fuga
# => "bar"

# , test: spike
not ok 4 - # path/to/examples/qunit_node.js:24
#
# assert.ok(longString === anotherLongString)
#           |          |   |
#           |          |   "yet another loooooooooooooooooooooooooooooooooooooooooooooooooooong message"
#           |          false
#           "very very loooooooooooooooooooooooooooooooooooooooooooooooooooong message"
#
# --- [string] anotherLongString
# +++ [string] longString
# @@ -1,15 +1,13 @@
# -yet anoth
# +very v
#  er
# +y
#   loo
#
# , test: spike
not ok 5 - # path/to/examples/qunit_node.js:26
#
# assert.ok(4 === piyo)
#             |   |
#             |   3
#             false
#
# [number] piyo
# => 3
# [number] 4
# => 4
# , test: spike
not ok 6 - # path/to/examples/qunit_node.js:28
#
# assert.ok(4 !== 4)
#             |
#             false
# , test: spike
not ok 7 - # path/to/examples/qunit_node.js:31
#
# assert.ok(falsyStr)
#           |
#           ""
# , test: spike
not ok 8 - # path/to/examples/qunit_node.js:34
#
# assert.ok(falsyNum)
#           |
#           0
# , test: spike
not ok 9 - # path/to/examples/qunit_node.js:38
#
# assert.ok(ary1.length === ary2.length)
#           |    |      |   |    |
#           |    |      |   |    3
#           |    |      |   ["aaa","bbb","ccc"]
#           |    2      false
#           ["foo","bar"]
#
# [number] ary2.length
# => 3
# [number] ary1.length
# => 2
# , test: spike
not ok 10 - # path/to/examples/qunit_node.js:39
#
# assert.deepEqual(ary1, ary2)
#                  |     |
#                  |     ["aaa","bbb","ccc"]
#                  ["foo","bar"]
# , expected: [
#   "aaa",
#   "bbb",
#   "ccc"
# ], got: [
#   "foo",
#   "bar"
# ], test: spike
not ok 11 - # path/to/examples/qunit_node.js:42
#
# assert.ok(5 < actual && actual < 13)
#             | |      |  |      |
#             | |      |  16     false
#             | 16     false
#             true
# , test: spike
not ok 12 - # path/to/examples/qunit_node.js:45
#
# assert.ok(5 < actual && actual < 13)
#             | |      |
#             | 4      false
#             false
# , test: spike
not ok 13 - # path/to/examples/qunit_node.js:48
#
# assert.ok(actual < 5 || 13 < actual)
#           |      |   |     | |
#           |      |   |     | 10
#           |      |   false false
#           10     false
# , test: spike
not ok 14 - # path/to/examples/qunit_node.js:58
#
# assert.ok(foo.bar.baz)
#           |   |   |
#           |   |   false
#           |   Object{baz:false}
#           Object{bar:#Object#}
# , test: spike
not ok 15 - # path/to/examples/qunit_node.js:59
#
# assert.ok(foo['bar'].baz)
#           |  |       |
#           |  |       false
#           |  Object{baz:false}
#           Object{bar:#Object#}
# , test: spike
not ok 16 - # path/to/examples/qunit_node.js:60
#
# assert.ok(foo[propName]['baz'])
#           |  ||        |
#           |  |"bar"    false
#           |  Object{baz:false}
#           Object{bar:#Object#}
# , test: spike
not ok 17 - # path/to/examples/qunit_node.js:64
#
# assert.ok(!truth)
#           ||
#           |true
#           false
# , test: spike
not ok 18 - # path/to/examples/qunit_node.js:68
#
# assert.ok(func())
#           |
#           false
# , test: spike
not ok 19 - # path/to/examples/qunit_node.js:76
#
# assert.ok(obj.age())
#           |   |
#           |   0
#           Object{age:#function#}
# , test: spike
not ok 20 - # path/to/examples/qunit_node.js:83
#
# assert.ok(isFalsy(positiveInt))
#           |       |
#           false   50
# , test: spike
not ok 21 - # path/to/examples/qunit_node.js:94
#
# assert.ok(sum(one, two, three) === seven)
#           |   |    |    |      |   |
#           |   |    |    |      |   7
#           6   1    2    3      false
#
# [number] seven
# => 7
# [number] sum(one, two, three)
# => 6
# , test: spike
not ok 22 - # path/to/examples/qunit_node.js:95
#
# assert.ok(sum(sum(one, two), three) === sum(sum(two, three), seven))
#           |   |   |    |     |      |   |   |   |    |       |
#           |   |   |    |     |      |   12  5   2    3       7
#           6   3   1    2     3      false
#
# [number] sum(sum(two, three), seven)
# => 12
# [number] sum(sum(one, two), three)
# => 6
# , test: spike
not ok 23 - # path/to/examples/qunit_node.js:96
#
# assert.ok(three * (seven * ten) === three)
#           |     |  |     | |    |   |
#           |     |  |     | |    |   3
#           |     |  |     | 10   false
#           |     |  7     70
#           3     210
#
# [number] three
# => 3
# [number] three * (seven * ten)
# => 210
# , test: spike
not ok 24 - # path/to/examples/qunit_node.js:110
#
# assert.ok(math.calc.sum(one, two, three) === seven)
#           |    |    |   |    |    |      |   |
#           |    |    |   |    |    |      |   7
#           |    |    6   1    2    3      false
#           |    Object{sum:#function#}
#           Object{calc:#Object#}
#
# [number] seven
# => 7
# [number] math.calc.sum(one, two, three)
# => 6
# , test: spike
1..24

Have fun!

power-assert's People

Contributors

artemgovorov avatar azu avatar dependabot[bot] avatar falsandtru avatar haru01 avatar leshakoss avatar numb86 avatar petamoriken avatar proloser avatar readmecritic avatar tetsuharuohzeki avatar twada avatar yang-wei avatar yuya-takeyama avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

power-assert's Issues

Provide an option to overwrite destination empowered assertion library

It seems like there is a great infrastructure around power-assert. More than this you provide a way for other assertion libraries to empowerment which is awesome! Nevertheless it seems like most of the instrumentors are power-assert-centric a bit (not a big surprise though =)). What I mean by that is implicit rewriting of require('assert') with hardcoded require('power-assert'). Would it be possible for all of these great instruments to provide an option to overwrite default power-assert with any other empowered assertion library? Alternatives that I see for such libraries either to ask their users to explicitly require them or maybe to recreate some of the instrumentors which seems the wrong way. What is your thoughts on this?

UPD Have proposed initial changes to the root instrumentors module via PR teppeis/empower-assert#3

Unable to get descriptive assertion messages on browsers

Does power-assert provide descriptive assertion messages on browsers?

Code

assert(0 === 1);
assert.deepEqual({foo: 0}, {foo: 1});

Expected(node)

          assert(0 === 1)
                   |
                   false
  assert.deepEqual({ foo: 0 }, { foo: 1 })
                   |           |
                   |           Object{foo:1}
                   Object{foo:0}

Actual(browser)

          assert(0 === 1)
                   |
                   false
        AssertionError: {"foo":0} deepEqual {"foo":1}

webpack use the legacy assert ( `deepStrictEqual` is not a function )

when use the [email protected] from [email protected] / [email protected], doesn't have the deepStrictEqual, it seems old assert is used.

import assert from 'assert';
import moduleName from '../src';

describe('moduleName', () => {
  it('spec1', () => {
    assert.deepEqual(moduleName(), { foo: null });// pass
    assert.deepStrictEqual(moduleName(), { foo: null });// error
  });
});

simulation environment: https://github.com/59naga/boilerplate-browser-babel

git clone https://github.com/59naga/boilerplate-browser-babel
cd boilerplate-browser-babel
git checkout 4804fd5432c626268ca2f148bc58e15bed7c0ec5

npm install
node -v && npm -v
# v5.10.0
#3.8.3
npm test
# TypeError: _powerAssert2.default.deepStrictEqual is not a function
#        at Context.<anonymous> (/Users/59naga/Downloads/boilerplate-browser-babel/test/index.js:71:28 <- webpack:///test/index.js:10:11)

one workaround, frozen the version of assert in 4.1.2 using the core-assert.

npm install 59naga/power-assert
npm test
# ...
# AssertionError:   # test/index.js:11
#
#   assert.deepStrictEqual(moduleName(), { foo: null })
#                          |                 |
#                          |                 Object{foo:null}
#                          Object{foo:undefined}

other than this, would you have any good solution?

英語に自信がないので、翻訳前の日本語も残しておきます。
webpack/babel-loaderからpower-assertを使用すると、deepStrictEqualを持たない、古いassertが使用されるようです。
解決方法の一つとして、core-assertに依存し、assertのバージョンを4.1.2に固定する方法があります。
これ以外で、何か良い解決方法はご存知でしょうか?

Type checking with assert.equal

I found with a surprise that assert.equal have both types as 'any' (even the strictEqual too):

export function equal(actual:any, expected:any, message?:string):void;

Why not do this way:

export function equal<T>(actual: T, expected: T, message?:string):void;

? It is better to catch any errors on compile time, not in the runtime, is not it?

Usage in Labjs

Hello, and thank you for this wonderful library !

We use lab a lot for testing. And it's as easy to use Power-assert with lab that it is with mocha.

I'd like to share the transform file needed to activate Power-assert, and I wonder the best way to do it.
1- Do I create a project (like you did with espower-loader) under my account ?
2- Do you create an empty project, so I can send you a PR ?
3- Do I send you the file (20 lines) and instructions ?

Thank you again !

Assertion error messages have local file paths

An assertion message has a local file path instead of variables.

expected:

assert(!!database_ === true);
       |||         |
       ||undefined false
       |true
       false

actual:

assert(!!dataD:/<dir>/<file>_ === true)
       |||         |
       ||undefined false
       |true
       false
...
... /power-assert.js:6093)

official support policy

We need to declare our official support policy.

refs #70

OUR SUPPORT POLICY

We support Node under maintenance. In other words, we stop supporting old Node version when their maintenance ends.
We also support modern browsers such as Chrome, Firefox, Safari, Edge etc.

This means that any other environment is not supported.

NOTE: If power-assert works in any of the unsupported environments, it is purely coincidental and has no bearing on future compatibility. Use at your own risk.

Cannot load module by SystemJS: Expected object

version: 1.4.1
SystemJS settings:

map = {
      "power-assert": "n:power-assert",
};
packages = {
   "power-assert": { main: "build/power-assert.js", defaultExtension: "js" },
}

My code

import * as assert from 'power-assert';

Which transpiles to:

var assert = require('power-assert');

And this line throws error:

Error: (SystemJS) Expected object
    TypeError: Expected object

Stack trace:

systemjs.src.js ~ line:3326

    if (exports && (exports.__esModule || exports instanceof Module))
      entry.esModule = loader.newModule(exports); // line:3326 <--- exports = function powerAssert ()
    // set module as 'default' export, then fake named exports by iterating properties
    else if (entry.esmExports && exports !== __global)
      entry.esModule = loader.newModule(getESModule(exports));
    // just use the 'default' export
    else
      entry.esModule = loader.newModule({ 'default': exports });

systemjs.src.js ~ line:892

    // 26.3.3.12
    newModule: function (obj) {
      if (typeof obj != 'object')
        throw new TypeError('Expected object'); // line:892 <!--- obj  = function powerAssert (), typeof obj = "function"

      var m = new Module();

Link to 26.3.3.12 of Loader-Spec
https://github.com/calvinmetcalf/Loader-Spec/blob/master/spec.md#263312-reflectloaderprototypenewmodule--obj-

obj is referencing to:

        powerAssert = function powerAssert () {
            return enhancement.apply(null, slice.apply(arguments));
        };

Power assert with ts-node

I prefer to use ts-node along with power assert, as I've already worked out how to get ts-node running the way I like.

I ran in to a few hurdles along the way, and created a new module to get ts-node working together with power-assert: https://github.com/tracecomms/espower-ts-node

The main thing I couldn't figure out was how to ignore errors and do a fast transpile instead of full type checking - which I find useful during dev, as it's quite a bit faster.

I know this is not really an issue as such, but though I'd add it here as I spent quite a bit of time trying to work this out, and hopefully either a) someone can let me know the simple solution I missed or b) this will help someone else!

Thanks for the amazing tool :-)

assert.deepEqual and truthy values

It seems that equals isn't always using strict equality:

assert.deepEqual({methodology: true}, {methodology: 1}) // doesn't fail
assert.equal(true, 1) // doesn't fail

Is it intended ?

failed to show error report when using Symbol

describe("test", () => {
  const FOO = Symbol("FOO");
  const BAR = Symbol("BAR");
  const BAZ= Symbol("BAZ");

  let obj = {
    [FOO]: 100,
    [BAR]: 100,
    [BAZ]: 200,
  };

  it("works", () => {
    assert(obj[FOO] === obj[BAR]);
  });
  it("does not works", () => {
    // this test fails
    assert(obj[FOO] === obj[BAZ]);
  });
});

I expected:

1) test does not works:

  assert(obj[FOO] === obj[BAZ])
         |  ||    |   |  ||    
         |  ||    |   |  |Symbol(BAZ)
         |  ||    |   |  200   
         |  ||    |   Object{FOO:100,BAR:100,BAZ:200}
         |  ||    false        
         |  |Symbol(FOO)             
         |  100                
         Object{FOO:100,BAR:100,BAZ:200}

  [number] obj[BAZ]
  => 200
  [number] obj[FOO]
  => 100

but got:

  1) test does not works:
     TypeError: Cannot read property 'filter' of null
      at Array.forEach (native)
      at Context.<anonymous> (test/build.js:22:5)

ReferenceError when assert interval timer of an class instance

test/a.js

 class A {
  constructor() {
    this.timer = setInterval(() => {}, 1000);
  }
}
const a = new A();
assert(a.timer);

index.js

'use strict';

require('intelli-espower-loader');
require('./test/a');

When I run node index.js, catch an error.

test/a.js:11
assert(a.timer);
       ^
ReferenceError: _rec1 is not defined
    at Object.<anonymous> (test/a.js:11:8)
    at Module._compile (module.js:570:32)
    at Object.extensions..js (/Users/gaoxiaochen/projj/github.com/node-modules/tcp-base/node_modules/.1.2.0@espower-loader/index.js:46:25)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/gaoxiaochen/projj/github.com/node-modules/tcp-base/index.js:2:1)
    at Module._compile (module.js:570:32)

power-assert make `assert()` of assert module silent

I've created reproduce repository.

Application code use assert module of Node Core.

index.js

// application code use `assert` module
const assert = require("assert");
export function hello(name) {
    assert(typeof name === "string");
    return "Hello " + name;
}

Test code:

const assert = require("power-assert");
import {hello} from "../src/index";
describe("hello", function () {
    it("should accept string", function () {
        hello(42);  // Should throw error via assert and fail tests.
    });
});

These code are transformed by babel + babel-plugin-espower.

.babelrc

{
  "presets": [
    "es2015"
  ],
  "env": {
    "development": {
      "plugins": [
        "babel-plugin-espower"
      ]
    }
  }
}

When I do this:

npm test

Expected

Fail test

Actual

Pass test :(


Reason

Application code is transformed to

"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };

var _powerAssertRecorder = function () { function PowerAssertRecorder() { this.captured = []; } PowerAssertRecorder.prototype._capt = function _capt(value, espath) { this.captured.push({ value: value, espath: espath }); return value; }; PowerAssertRecorder.prototype._expr = function _expr(value, source) { return { powerAssertContext: { value: value, events: this.captured }, source: source }; }; return PowerAssertRecorder; }();

exports.hello = hello;
// application code use `assert` module
var assert = require("assert");
function hello(name) {
    var _rec = new _powerAssertRecorder();

    assert(_rec._expr(_rec._capt(_rec._capt(typeof name === "undefined" ? "undefined" : _typeof(name), "arguments/0/left") === "string", "arguments/0"), {
        content: "assert(typeof name === \"string\")",
        filepath: "src/index.js",
        line: 4
    }));
    return "Hello " + name;
}
//# sourceMappingURL=index.js.map

_rec._expr return object.

    var assert = require("assert");
    var object = _rec._expr(_rec._capt(_rec._capt(typeof name === "undefined" ? "undefined" : _typeof(name), "arguments/0/left") === "string", "arguments/0"), {
        content: "assert(typeof name === \"string\")",
        filepath: "src/index.js",
        line: 4
    });
    assert(object);

So, assert(Object) never throw error. It causes this issue.

Do you have any solution?

assert.deepEqual() with tolerance

I would like to use assert.deepEqual() to compare two JSON objects, but the objects contain floating-point numbers that are only roughly the same. Is there some way to compare those two objects with a tolerance when comparing numbers? i.e. when the algorithm compares numbers it will accept a difference of up to 0.001% or something like that.

More descriptive results for `typeof` expressions

So, something like this is a pretty common pattern:

assert(typeof wrap === 'function')

    AssertionError:   # giraphe.es6.js:61

assert(typeof wrap === 'function')
       |           |
       "object"    false

--- [string] 'function'
+++ [string] typeof wrap
@@ -1,8 +1,6 @@
-function
+object


    + expected - actual

    -false
    +true

Although this works, I feel that this could easily be extended with more useful information: for instance, in most failing assertions, there's information about the object under test; but specifically in typeof's case, that gets lost, and it gets treated as a simple comparison of two static strings.

Here's something like what I'd expect to see (hastily cobbled together from the results for assert(wrap === 'function'), because it was an easy change :P:

    AssertionError:   # giraphe.es6.js:61

assert(typeof wrap === 'function')
       |      |    |
       |      |    false
       |      Object{}
       "object"

[string] 'function'
=> "function"
[Object] wrap
=> Object{}

--- [string] 'function'
+++ [string] typeof wrap
@@ -1,8 +1,6 @@
-function
+object


    + expected - actual

    -false
    +true

New API for Design By Contract

A function cannot assert own return value with no changes. I want the solution for it weak point.

Currently

  • Need changes for postcondition(need temporary variable).
  • Cannot provide descriptive assertion messages.
function add(a, b) {
  // precondition
  assert(typeof a === 'number' && isNaN(a));
  assert(typeof b === 'number' && isNaN(b));
  // return a + b;
  var ret = a + b;
  // postcondition
  assert(ret === b + a);
  return ret;
}

Method chaining

Not simple, not easy.

function add(a, b) {
  // precondition
  assert(typeof a === 'number' && isNaN(a));
  assert(typeof b === 'number' && isNaN(b));
  // postcondition and body
  return assert.return(a + b).equal(b + a);
}

Placeholder

Beautiful. Targeted for closest return statement only.

source:

function add(a, b) {
  // precondition
  assert(typeof a === 'number' && isNaN(a));
  assert(typeof b === 'number' && isNaN(b));
  // for all condition(however, code flow will be reversed)
  assert(assert.lookbehind === b + a); // => assert(a + b === b + a);
  // body
  return a + b;
  // postcondition
  assert(assert.lookahead === b + a); // => assert(a + b === b + a);
  assert(assert.lookahead === a + b); // => assert(a + b === a + b);
}

pre-espowered:

// Design A: Direct expansion
function add(a, b) {
  // precondition
  assert(typeof a === 'number' && isNaN(a));
  assert(typeof b === 'number' && isNaN(b));
  // for all condition(however, code flow will be reversed)
  assert(assert.lookbehind === b + a); // => assert(a + b === b + a);
  var actual = a + b; // any unique variable
  // postcondition
  // grouping
  assert(actual === b + a); // from lookbehind
  assert(actual === b + a); // from lookahead
  assert(actual === a + b); // from lookahead
  return actual;
}

// Design B: Use closure
function add(a, b) {
  // precondition
  assert(typeof a === 'number' && isNaN(a));
  assert(typeof b === 'number' && isNaN(b));
  // for all condition(however, code flow will be reversed)
  assert(assert.lookbehind === b + a); // => assert(a + b === b + a);
  // body
  return (function (actual) {
    // postcondition
    // grouping
    assert(actual === b + a); // from lookbehind
    assert(actual === b + a); // from lookahead
    assert(actual === a + b); // from lookahead
    return actual;
  })(a + b);
}

emit:

function add(a, b) {
  return a + b;
}

Unable to parse emojis

So cute 🍨 🌟 💓

assert("☺⛺✅㊗🆘🌀🌟🌾🍨🍬🍰🎃🎄🎍🎨🏃💞💤😭😒" === "☺⛺✅㊗🆘🌀🌟🌾🍨🍬🍰🎄🎍🎨🏃💞💤😭😒");
URIError: URI malformed
 at encodeURI (native)

test files which are not in the 'test' dir than seems won't work

good one:

image

bad one:

image

test with same file: power.js

var assert = require('assert');

describe('Array', function(){
    beforeEach(function(){
        this.ary = [1,2,3];
    });
    describe('#indexOf()', function(){
        it('should return index when the value is present', function(){
            var zero = 0, two = 2;
            assert(this.ary.indexOf(zero) === two);
        });
    });
});

I have one project that the test files are not in the test dir .

please help me. thanks!

String comparing

Hi. I need to compare multiline strings but the output is too hard to analyze. It the a way to make it more visual. For example fast-diff seems interesting.

The second problem is compare on windows. When read input or output from disk it contains \r\n linebreaks. Every time I should to add .replace(/\r\n/g, '\n')

`global.assert = require('assert')` problem

global.assert = require('assert');
describe('test/showcase.test.js', () => {
  const arr = [ 1, 2, 3 ];

  it('power-assert', () => {
    assert(arr[1] === 10);
  });
});

then the unit test passed...

Question: disabling graphs

Is it possible to disable it? In this example, I'd like to see the first and third parts, just not the second part.

  assert(this.ary.indexOf(zero) === two)
              |   |       |     |   |
              |   |       |     |   2
              |   -1      0     false
              [1,2,3]
  [number] two
  => 2
  [number] this.ary.indexOf(zero)
  => -1

Cannot capture not invokable method error

var o = {};
assert(o.m());
TypeError: assert._capt(...).m is not a function
var o = {};
assert(assert._expr(assert._capt(assert._capt(o, 'arguments/0/callee/object').m(), 'arguments/0'), {
    content: 'assert(o.m())',
    ...
}));

Are all dependencies required at runtime?

I have some tests that I'd like to run both in node and the browser. The tests are compiled using Babel (with babel/register to run in node, and with webpack's Babel loader for the browser).

My assumption was that I could just add babel-plugin-espower to my .babelrc plugins in order to apply the transformation for both cases. This worked, however, the browser build is including power-assert's dependencies, including acorn (some of which are causing webpack to generate build warnings). I think I understand why this is happening; my tests require power-assert, so naturally the dependencies are getting bundled.

So my question is, are all of the dependencies necessary at run time or are they just required for the transform? (If just for the transform is there a recommended way to omit them?)

I hope this is the right forum for this question! Thanks so much for such an awesome project!

Cannot capture UpdateExpression like ++foo

class C {
  count_ = {};
  count() {
    return this.count_;
  }
}
var counter = new C();
assert(++counter.count_ === counter.count());

expected:

          assert(++counter.count_ === counter.count())
                 | |       |      |   |       |
                 | |       |      |   |       Object{}
                 | |       |      |   C{count_:#Object#}
                 | |       |      false
                 | |       Object{}
                 | C{count_:#Object#}
                 NaN

actual:

          assert(++counter.count_ === counter.count())
                 |                |   |       |
                 |                |   |       NaN
                 |                |   C{count_:NaN}
                 NaN              false

other:

          assert(+counter.count_ === counter.count())
                 ||       |      |   |       |
                 ||       |      |   |       Object{}
                 ||       |      |   C{count_:#Object#}
                 ||       |      false
                 ||       Object{}
                 |C{count_:#Object#}
                 NaN

Unable to compose power-assert + espower in vanilla node 7 or 8

I am trying to use power-assert to get pretty assert output in node, without using mocha or babel.

I'm trying to implement assertions by reading the documentation, but haven't been able to get it working so far.

Here is my attempt at a "vanilla node" (no mocha) seed: https://github.com/TehShrike/power-assert-espower-repro

entry point:

require('espower-loader')({
	pattern: 'test/*.js',
})

require('./test/test.js')

test/test.js:

const assert = require('power-assert')

const test = () => {
	const value1 = true
	const value2 = 3
	assert.deepEqual({ value: value1 }, { value: value2 })
}

test()

Instead of a nice pretty error message, I get:

/Users/josh/code/power-assert-espower-repro/node_modules/empower-core/lib/decorator.js:110
        ret = func.apply(thisObj, args);
                   ^
AssertionError: { value: true } deepEqual { value: 3 }
    at Decorator._callFunc (/Users/josh/code/power-assert-espower-repro/node_modules/empower-core/lib/decorator.js:110:20)
(snip)

What am I missing? I'm guessing this is a documentation/implementation issue, and not an actual bug.

(node 7.6.0)

Seems not working, but I have no idea.

Hi, I just tried power-assert, it is looks great.

But I can't reproduce power-assert print, I have no idea why.

Could you give me some help?

  // It doesn't print
  assert(this.ary.indexOf(zero) === two)
              |   |       |     |   |
              |   |       |     |   2
              |   -1      0     false
              [1,2,3]

My package.json

{
  "name": "power-assert",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "@types/mocha": "^2.2.40",
    "@types/power-assert": "^1.4.29",
    "espower-typescript": "^8.0.0",
    "intelli-espower-loader": "^1.0.1",
    "mocha": "^3.2.0",
    "power-assert": "^1.4.2"
  },
  "scripts": {
    "test": "mocha --require intelli-espower-loader src/**/*.spec.js"
  }
}

index.spec.js

const assert = require('power-assert')

describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert(3 === [1, 2, 3].indexOf(4))
    })
  })
})

image

MacOS 10.12.4
node v6.9.1
yarn 0.20.3

Support SequenceExpression (i.e., comma operator)

code:

assert((-0, -1) === -0 + (-1));

expected:

  assert((-0, -1) + 1 === -0 + (-1))
         ||   |   |   |   |  |  |
         |0   -1  |   |   |  |  -1
         -1       |   |   0  -1
                  0   false

actual:

  assert((-0, -1) + 1 === -0 + -1)
                  |   |   |  | |
                  |   |   |  | -1
                  |   |   0  -1
                  0   false

Runtime interrogation of assertions-enabled status

So, for relatively simple assertions, it's possible to keep the entire assertion within the single assert( … ) statement; but I have a few places in my code where monstrosities like the following arise:

assert( null != blah.first_complicated_state() ?
   (null != blah.second_complicated_state() ?
      _.every(blah, element => ...)
    : _.every(blah, element => ...))
 : _.every(blah, element => ...)
)

Basically, sometimes, there's an expensive operation (i.e. not something I can safely leave laying around outside the assert, to end up in production code) that's necessary to choose how to assert something else.

Since I suspect asking for a to-be-compiled-out assert { … } block is unlikely to be in-line with the project goals, can I simply get a runtime-cheap boolean-property that I can test, to preform more complicated assertions that won't be compiled-out?

if (assert.enabled) {
   if (blah.first_complicated_state())
      assert( ... )

   else if (blah.second_complicated_state())
      assert( ... )
   ...
}

Async assertion does not work on (grunt?) karma when I use multiple karma preprocessors

Async assertion is always successful under the this code.

    it('async assertion', function (done) {
      setTimeout(() => {
        console.log(assert(false === true), assert); // LOG: undefined, function powerAssert() { ... }
        done();
      }, 1);
    });
// gruntfile.js
    karma: {
      options: {
        configFile: 'karma.conf.js',
        preprocessors: {
          'test/fixture/*.html': ['html2js'],
          'test/cov/*.js': ['coverage', 'espower']
        }
      },
      ph: {
        browsers: ['PhantomJS'],
        singleRun: true
      },
      dev: {
        browsers: ['PhantomJS'],
        preprocessors: {
          'test/cov/*.js': ['espower']
        },
        singleRun: false
      }
    },
// karma.conf.js
    preprocessors: {
      'test/cov/*.js': ['coverage', 'espower']
    },
$ grunt karma:dev

以下詳細を英語がつたないので日本語で失礼します。
同期プロセスでのアサーションは正常に動作しますが非同期プロセスでは上記のとおりassert(false === true)が成功します。このバグは特殊な条件下で発生するようで、プリプロセッサの位置や組み合わせを変えると発生しません。grunt-karmaが内部的に生成するkarmaの設定が原因のような気がします。このバグが発生したプロダクトは未公開ですが対応していただけるようでしたら後ほど早めに公開してもってこようと思います。

Incorrect `instanceof` assertion messages

expected

  assert(null instanceof Object)
              |          |
              false      #function#
  assert(void 0 instanceof Object)
         |      |          |
         |      false      #function#
         undefined

actual

  assert(null instanceof Object)
         |               |
         false           #function#
  assert(void 0 instanceof Object)
         |                 |
         |alse             #function#
         undefined

I'm not getting (No descriptive assertion messages)

windows 8, node v.0.11.13, power-assert 0.9.0
Runnig example test for node, mocha gives standart output without descriptive assertion messages.

assert(this.ary.indexOf(zero) === two)
                |   |       |     |   |
                |   |       |     |   2
                |   -1      0     false
                [1,2,3]

^ I don't see it.
What am I doing wrong?

convert relative filepath for security reason

power-asserted test result includes filepath with 'full path' like this.

assert.strictEqual(assert._expr(assert._capt(typeof res, 'arguments/0'), {
  content: 'assert.strictEqual(typeof name, \'string\')',
  filepath: '/home/username/path/to/project/and/file.js',
  line: 22
}), 'string');

file path with full path is kind of sensitive information in server or developer machine.
if user doesn't know this behavior, it may cause some security issue.
(for example, some could forgot adding build result to gitignore and push to public repository.)

I think this information is only a project specific.
so it seems better for me to use relative path of test file or project or configurable base bath.

any comments ?

ReferenceError when assert object extended Map

test/a.js

'use strict';

const assert = require('assert');

class AMap extends Map {
  get(name) {
    console.log(name);
    return super.get(name);
  }
}
const map = new AMap();
map.set('a', true);
assert(map.has('a'));

index.js

'use strict';

require('intelli-espower-loader');
require('./test/a.js');

When I run node index.js, catch an error.

test/a.js:13
assert(map.has('a'));
       ^
ReferenceError: _rec1 is not defined
    at Object.<anonymous> (test/b.js:13:8)
    at Module._compile (module.js:570:32)
    at Object.extensions..js (/Users/popomore/code/tmp/b/node_modules/.1.2.0@espower-loader/index.js:46:25)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/popomore/code/tmp/b/index.js:4:1)
    at Module._compile (module.js:570:32)

deepStrictEqual more descriptive output when failing

There seems to be lacking output for assert.deepStrictEqual compared to assert.deepEqual.
If you provide a 'descriptive message when assertion is failed' only that message will be printed:

descriptive message

If you don't provide a message to the method, the compared objects will be printed like this:

{object1} deepStrictEqual {object2}

But in both cases you want to be able to compare them in the output (somewhat like deepEqual).

Besides this if the objects (that are compared) are somewhat 'big' they wont display completely (when not providing a message):

{"startupExtent":{"extent":[139722.24000000002,407339.51999999996,159774.72,416102.39999999997],"srs":"EPSG:28992"},"userSrs":"E deepStrictEqual {"startupExtent":{"extent":[139722.24000000002,407339.51999999996,159774.72,416102.39999999997],"srs":"EPSG:28992"},"userSrs":"E

actual object:
var object = { startupExtent: {"extent":[139722.24000000002,407339.51999999996,159774.72,416102.39999999997],"srs":"EPSG:28992"}, userSrs: 'EPSG:28992', searchHistory: [], mapShowScaleBarDefault: true, mapShowZoomSliderDefault: true, }

Getter for customized options

Hi Lions!

In my karma plugin, I'm testing customized options only by comparing stdout with passed options, so it would be nice if I can access to the options I passed though assert.customize, to develop plugins in my case. It can be something like assert.options to return extend(empowerOptions, options.assertion) I guess.

[discussion] deepEqual on arrays

can we get fancy diff while deepEqual-ing two arrays?

right now, it's not neither fancy, neither helpful at all

  1. index › should esDepsResolved

  t.deepEqual(_, expected)
              |  |
              |  [#Object#,#Object#,#Object#,#Object#,#Object#,#Object#]
              [#Object#,#Object#,#Object#,#Object#,#Object#,#Object#]

      resolved: '/Users
        Decorator._callFunc (/Users/iamstarkov/projects/es-deps-resolved/node_modules/.store/[email protected]/_/lib/decorator.js:110:20)
        Decorator.concreteAssert (/Users/iamstarkov/projects/es-deps-resolved/node_modules/.store/[email protected]/_/lib/decorator.js:103:17)
        Object.decoratedAssert [as deepEqual] (/Users/iamstarkov/projects/es-deps-resolved/node_modules/.store/[email protected]/_/lib/decorate.js:49:30)
        index.js:29:7

so, i have to do

  .then(_ => {
    t.deepEqual(_[0], expected[0]);
    t.deepEqual(_[1], expected[1]);
    t.deepEqual(_[2], expected[2]);
    t.deepEqual(_[3], expected[3]);
    t.deepEqual(_[4], expected[4]);
    t.deepEqual(_[5], expected[5]);
  }));

instead of just this

  .then(_ => t.deepEqual(_, expected)));

webpack: deepStrictEqual is not a function

git clone https://github.com/59naga/boilerplate-browser-babel
cd boilerplate-browser-babel
git checkout 4804fd5432c626268ca2f148bc58e15bed7c0ec5

npm install
npm test
# TypeError: _powerAssert2.default.deepStrictEqual is not a function
        at Context.<anonymous> (/Users/59naga/Downloads/boilerplate-browser-babel/test/index.js:71:28 <- webpack:///test/index.js:10:11)

high-level assertions?

I absolutely love, love, love power-assert.

One thing I'm a bit unsure about is how to test promises, though. In chai, for example, I can do

expect(promise).to.be.rejectedWith(...)

but with power-assert I need much more code. Is adding higher-level assertions on the roadmap, or can I build these myself somehow?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.