Technology moves fast! ⚡ Don't get left behind.🚶 Subscribe to our mailing list to keep up with latest and greatest in open source projects! 🏆


Subscribe to our mailing list

expect.js

Minimalistic BDD-style assertions for Node.JS and the browser.

Subscribe to updates I use expect.js


Statistics on expect.js

Number of watchers on Github 1856
Number of open issues 82
Average time to close an issue 3 months
Main language JavaScript
Average time to merge a PR 3 months
Open pull requests 35+
Closed pull requests 26+
Last commit over 4 years ago
Repo Created over 7 years ago
Repo Last Updated over 1 year ago
Size 692 KB
Organization / Authorautomattic
Contributors20
Page Updated
Do you use expect.js? Leave a review!
View open issues (82)
View expect.js activity
View on github
Fresh, new opensource launches 🚀🚀🚀
Trendy new open source projects in your inbox! View examples

Subscribe to our mailing list

Evaluating expect.js for your project? Score Explanation
Commits Score (?)
Issues & PR Score (?)

Expect

Minimalistic BDD assertion toolkit based on should.js

expect(window.r).to.be(undefined);
expect({ a: 'b' }).to.eql({ a: 'b' })
expect(5).to.be.a('number');
expect([]).to.be.an('array');
expect(window).not.to.be.an(Image);

Features

  • Cross-browser: works on IE6+, Firefox, Safari, Chrome, Opera.
  • Compatible with all test frameworks.
  • Node.JS ready (require('expect.js')).
  • Standalone. Single global with no prototype extensions or shims.

How to use

Node

Install it with NPM or add it to your package.json:

$ npm install expect.js

Then:

var expect = require('expect.js');

Browser

Expose the index.js found at the top level of this repository.

<script src="expect.js"></script>

API

ok: asserts that the value is truthy or not

expect(1).to.be.ok();
expect(true).to.be.ok();
expect({}).to.be.ok();
expect(0).to.not.be.ok();

be / equal: asserts === equality

expect(1).to.be(1)
expect(NaN).not.to.equal(NaN);
expect(1).not.to.be(true)
expect('1').to.not.be(1);

eql: asserts loose equality that works with objects

expect({ a: 'b' }).to.eql({ a: 'b' });
expect(1).to.eql('1');

a/an: asserts typeof with support for array type and instanceof

// typeof with optional `array`
expect(5).to.be.a('number');
expect([]).to.be.an('array');  // works
expect([]).to.be.an('object'); // works too, since it uses `typeof`

// constructors
expect([]).to.be.an(Array);
expect(tobi).to.be.a(Ferret);
expect(person).to.be.a(Mammal);

match: asserts String regular expression match

expect(program.version).to.match(/[0-9]+\.[0-9]+\.[0-9]+/);

contain: asserts indexOf for an array or string

expect([1, 2]).to.contain(1);
expect('hello world').to.contain('world');

length: asserts array .length

expect([]).to.have.length(0);
expect([1,2,3]).to.have.length(3);

empty: asserts that an array is empty or not

expect([]).to.be.empty();
expect({}).to.be.empty();
expect({ length: 0, duck: 'typing' }).to.be.empty();
expect({ my: 'object' }).to.not.be.empty();
expect([1,2,3]).to.not.be.empty();

property: asserts presence of an own property (and value optionally)

expect(window).to.have.property('expect')
expect(window).to.have.property('expect', expect)
expect({a: 'b'}).to.have.property('a');

key/keys: asserts the presence of a key. Supports the only modifier

expect({ a: 'b' }).to.have.key('a');
expect({ a: 'b', c: 'd' }).to.only.have.keys('a', 'c');
expect({ a: 'b', c: 'd' }).to.only.have.keys(['a', 'c']);
expect({ a: 'b', c: 'd' }).to.not.only.have.key('a');

throw/throwException/throwError: asserts that the Function throws or not when called

expect(fn).to.throw(); // synonym of throwException
expect(fn).to.throwError(); // synonym of throwException
expect(fn).to.throwException(function (e) { // get the exception object
  expect(e).to.be.a(SyntaxError);
});
expect(fn).to.throwException(/matches the exception message/);
expect(fn2).to.not.throwException();

withArgs: creates anonymous function to call fn with arguments

expect(fn).withArgs(invalid, arg).to.throwException();
expect(fn).withArgs(valid, arg).to.not.throwException();

within: asserts a number within a range

expect(1).to.be.within(0, Infinity);

greaterThan/above: asserts >

expect(3).to.be.above(0);
expect(5).to.be.greaterThan(3);

lessThan/below: asserts <

expect(0).to.be.below(3);
expect(1).to.be.lessThan(3);

fail: explicitly forces failure.

expect().fail()
expect().fail("Custom failure message")

Using with a test framework

For example, if you create a test suite with mocha.

Let's say we wanted to test the following program:

math.js

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

Our test file would look like this:

describe('test suite', function () {
  it('should expose a function', function () {
    expect(add).to.be.a('function');
  });

  it('should do math', function () {
    expect(add(1, 3)).to.equal(4);
  });
});

If a certain expectation fails, an exception will be raised which gets captured and shown/processed by the test runner.

Differences with should.js

  • No need for static should methods like should.strictEqual. For example, expect(obj).to.be(undefined) works well.
  • Some API simplifications / changes.
  • API changes related to browser compatibility.

Running tests

Clone the repository and install the developer dependencies:

git clone git://github.com/LearnBoost/expect.js.git expect
cd expect && npm install

Node

make test

Browser

make test-browser

and point your browser(s) to http://localhost:3000/test/

Credits

(The MIT License)

Copyright (c) 2011 Guillermo Rauch <guillermo@learnboost.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

3rd-party

Heavily borrows from should.js by TJ Holowaychuck - MIT.

expect.js open issues Ask a question     (View All Issues)
  • almost 3 years .eql() is broken in ES6
  • almost 3 years Message not clear enough
  • almost 3 years expect(...).to.be.closeTo(expected, delta)
  • over 3 years TypeError: Cannot assign to read only property 'length'
  • over 3 years expect(fn).withArgs(...) rebinds `this` in fn
  • over 3 years Set comparison with eql is wrong
  • almost 4 years eql does not work if an array item is undefined in IE8
  • about 4 years RangeError when comparing two objects with eql
  • about 4 years Value be Something OR SomethingElse
  • about 4 years expect(null).to.eql(undefined)
  • about 4 years Add a way to check a value is eql to someone
  • about 4 years AssertionError
  • over 4 years TypeError: Object #<Assertion> has no method 'throw'
  • over 4 years Is it possible to show descriptive text if a test fail?
  • over 4 years Add case-insensitive equality check
  • over 4 years have.property(key, value) asserts "==="-equality
  • almost 5 years Allow by-string matching in throwError
  • almost 5 years Is the documentation wrong?
  • about 5 years is it possible to check a object properties with regex?
  • about 5 years check if something is a buffer
  • about 5 years >= and <= support?
  • over 5 years expect(fn).to.throwError() steals context
  • over 5 years "Not have keys" assertion seems unintuitive
  • over 5 years Is this module abandoned?
  • over 5 years TypeError: Object explicit failure has no method 'call'
  • over 5 years Approximate floating point value
  • over 5 years `expect` return value can't be reused with `.to.have.property`.
  • over 5 years Way to Override Output Formatting
  • over 5 years 'withArgs' allways runs in global scope
  • over 5 years null == undefined
expect.js open pull requests (View All Pulls)
  • Fix repository URL
  • Add containEql() to support deep equality
  • I think this method does not exist ?
  • Fix eql for ES6 Set objects
  • Adds support for properties()
  • added support for Promises
  • Add component.json file
  • Add license attribute
  • allow .match to accept strings
  • Fixed test-browser by updating /expect.js to /index.js and...
  • `.which` property
  • ThrowException can accept string to match exception message
  • Added new test methods lessThanOrEqual() and greaterThanOrEqual()
  • Make it clear that `fail` doesn't work without intermediary
  • add spm support
  • Possibly clarify the usage in the browser?
  • Enforce `arguments` constraint reflexively
  • Update test environments to load library correctly
  • added about/near/approximately functionality
  • added subobject check to the contain assertion
  • Add test for cyclic structures
  • Add between as alias to within
  • Add startsWith and endsWith
  • not.throwError with regexp matching should only fail if an error is actually thrown
  • README.md throwError example with better clarity
  • Add means for checking that expected objects are contained in the actual array (order doesn't matter)
  • Allow .and chaining for .ok and .throwError
  • expose flags and keep assertion chain
  • fix "sort of comparison" for dom nodes
  • Added an exists assertion
  • should.js repo was moved.
  • Add license info to package.json
  • Fix for Chrome bug trying to access `selectionStart` on certain `<input>` elements
  • Added license MIT to package.json
  • fix of Type Error on first line
expect.js questions on Stackoverflow (View All Questions)
  • making jasmine to work with expect.js
  • how to pass a test with expect.js async done() taking an error?
  • Expect.js validation issue on Codeacademy Lesson
  • set equivalence with expect.js
expect.js list of languages used
Other projects in JavaScript