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

Related tags

Assertion expect.js
Overview

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 <[email protected]>

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.

Comments
  • Release version 0.2.1

    Release version 0.2.1

    There are at least four issues (#42, #65, #68, #87) relating to problems with versions being out of sync (GitHub vs Node vs version number in the source). There also has not been a release since 2012, although several additions have come into play, which makes maintaining tests a hassle.

    This pull request simply updates the version numbers and the History file of changes.

    Now all we need is for @LearnBoost (actually @guille ) to update the NPM module :+1:

    opened by fatso83 10
  • Fix isRegExp bug in some edge cases

    Fix isRegExp bug in some edge cases

    var s = '' + re; // This fails for the object types mentioned bellow
    
    [object XMLHttpRequestExceptionPrototype]
    [object DOMExceptionPrototype]
    [object DOMTokenListPrototype]
    [object RangePrototype]
    [object HTMLAnchorElementPrototype]
    [object RangeExceptionPrototype]
    [object XPathExceptionPrototype]
    [object EventExceptionPrototype]
    [object WebKitCSSMatrixPrototype]
    [object SVGExceptionPrototype]
    [object XMLHttpRequestExceptionPrototype]
    [object DOMExceptionPrototype]
    [object DOMTokenListPrototype]
    [object RangePrototype]
    [object HTMLAnchorElementPrototype]
    [object RangeExceptionPrototype]
    [object XPathExceptionPrototype]
    [object EventExceptionPrototype]
    [object WebKitCSSMatrixPrototype]
    [object SVGExceptionPrototype]
    
    opened by satazor 8
  • Fixed the fail function

    Fixed the fail function

    fail() function did not work. Tests failed. Updated and tested on Windows and Ubuntu.

    Also adjusted some stuff to allow running the tests on windows using the added batch files.

    opened by pghalliday 7
  • Added almostEqual() assert

    Added almostEqual() assert

    Added almostEqual() assert for checking for near-equality, useful for testing results of numeric calculations with precision rounding errors. Test code becomes much more compact than when using within() assert directly.

    Also wrote some some unit tests that should cover most potential bugs if not all.

    opened by magwo 5
  • Examples says that you can expect 5 to be a Number but it fails

    Examples says that you can expect 5 to be a Number but it fails

    Just require

    expect = require('expect.js');
    expect(5).to.be.a(Number);
    

    It throws an execption:

    Error: expected 5 to be an instance of Number
        at Assertion.assert (expect.js/index.js:96:13)
        at Assertion.a.Assertion.an [as a] (expect.js/index.js:279:12)
        at Function.a (expect.js/index.js:499:17)
        at repl:1:17
        at REPLServer.self.eval (repl.js:110:21)
        at repl.js:249:20
        at REPLServer.self.eval (repl.js:122:7)
        at Interface.<anonymous> (repl.js:239:12)
        at Interface.EventEmitter.emit (events.js:95:17)
        at Interface._onLine (readline.js:202:10)
    

    I'm using version 0.3.1

    opened by pmarques 4
  • Added Component.json

    Added Component.json

    Hi! I've added a component.json, so that expect.js can be installed via component super-simply. expect.js is already in the component.io registry, but it's missing the component.json definition.

    If you would like to add component(1) support, feel free to merge this! If you have concerns, you could let me know and we could discuss.

    Thanks for making expect! I like it, and my team rocks it. :)

    -Milan

    opened by milaniliev 4
  • Library Version 0.0.2 Available on NPM fails to load

    Library Version 0.0.2 Available on NPM fails to load

    Getting the following error with the currently released version:

    Derp:website cheezburger$ mocha

    /Users/cheezburger/Projects/website/node_modules/expect/expect.js:17 expect.version = '0.0.2'; ^ ReferenceError: expect is not defined at /Users/cheezburger/Projects/website/node_modules/expect/expect.js:17:3 at Object. (/Users/cheezburger/Projects/website/node_modules/expect/expect.js:75:2) at Module._compile (module.js:449:26) at Object.Module._extensions..js (module.js:467:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Module.require (module.js:362:17) at require (module.js:378:17) at Command. (/usr/local/lib/node_modules/mocha/bin/_mocha:151:3) at Command.EventEmitter.emit (events.js:126:20)

    Looks like the expect object is scoped to the export and not available in the module directly.

    opened by NotMyself 4
  • Leaked Globals

    Leaked Globals

    When using expect.js with Mocha and using the throwException assertion, Mocha fails on "leaked globals" for vars message and name. To verify, if I console.log those global vars in my test, they do indeed have values attached to them from throwException for my particular exception's name and message fields.

    I'm testing a custom error object, which I've defined as follows (compiled output for CoffeeScript):

    (function() {
      var AbstractMethodError,
        __hasProp = {}.hasOwnProperty,
        __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
    
      AbstractMethodError = (function(_super) {
    
        __extends(AbstractMethodError, _super);
    
        function AbstractMethodError(message) {
          this.message = message || 'You tried to call an abstract method. You must override this method in your subclass.';
          this.name = 'AbstractMethodError';
        }
    
        return AbstractMethodError;
    
      })(Error);
    
    }).call(this);
    

    In looking at the expect.js code for throwException, I'm not sure I understand how the name and message vars are being attached to the global scope. Any thoughts or suggestions?

    opened by semperos 4
  • Problematic Package Name

    Problematic Package Name

    Two problems I've encountered relating to the name of this package:

    1.) I easily overlooked that the function name didn't match the package so incorrectly attempted installing with npm install expect which is actually a different package. Once I got the correct package, I still tripped over having to assign the function to a variable with a different name in order to execute.

    2.) I can't use the --require option of mocha with expect.js because the function name needs to match the package.

    Proposal: Convince onirame to relinquish the name of expect to you. His module appears to be pretty thin and unmaintained for three months. A lesser alternative would be to rename the package and the calling function to something else like 'expectjs' or 'expectthis'.

    opened by uipoet 3
  • throwException() improvement

    throwException() improvement

    I have a project that does a lot of validations, and if something wrong happens an error is thrown.

    If I got a test that asserts an exception being throw and if I accidentally call an undefined method inside the code being tested, the assert passes because it was expected to throw an error. To solve this, we could somehow let users specify the expected type of error (ReferenceError, TypeError, etc). But again, this won't be enough, because one could want to test against the error.code or error.message. This test could be direct or using a regular expression to test for dynamic error messages like 'Method foo() is incomplete ..'.

    What you guys think?

    opened by satazor 3
  • Compatibility with ES modules

    Compatibility with ES modules

    I have been authoring some of the new code in ES modules now that nodejs supports those natively. However turns out there is no good story around testing ES modules without transpiling them first.

    To overcome this I have forked this library turning it into ES modules and using combination of rollup + export maps to make it usable from commonjs modules as well. In addition I have also:

    • Added typedefs to provide code intellisencse and out of the box support for ts.
    • Added optional message argument to expect which I discovered many of the existing tests written for chai used.

    Please let me know if you have any interest in taking these changes, otherwise I'll publish my fork under the different name so I could use it across multiple libraries I'm working on.

    opened by Gozala 0
Owner
Automattic
We are passionate about making the web a better place.
Automattic
🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

React Testing Library Simple and complete React DOM testing utilities that encourage good testing practices. Read The Docs | Edit the docs Table of Co

Testing Library 17.3k Jan 4, 2023
Test spies, stubs and mocks for JavaScript.

Sinon.JS Standalone and test framework agnostic JavaScript test spies, stubs and mocks (pronounced "sigh-non", named after Sinon, the warrior). Compat

Sinon.JS 9.2k Jan 4, 2023
⚡️The Fullstack React Framework — built on Next.js

The Fullstack React Framework "Zero-API" Data Layer — Built on Next.js — Inspired by Ruby on Rails Read the Documentation “Zero-API” data layer lets y

⚡️Blitz 12.5k Jan 4, 2023
BDD / TDD assertion framework for node.js and the browser that can be paired with any testing framework.

chai Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework. For more in

Chai.js Assertion Library 7.8k Dec 30, 2022
A PostgreSQL client with strict types, detailed logging and assertions.

Slonik A battle-tested PostgreSQL client with strict types, detailed logging and assertions. (The above GIF shows Slonik producing query logs. Slonik

Gajus Kuizinas 3.6k Jan 3, 2023
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Assertions package for Japa. Built on top of Chai.Assert

@japa/assert Assertion library built on top of Chai.assert An assertion library built on top of Chai.assert with small tweaks and additional features

Japa.dev 7 May 4, 2022
Cypress Boilerplate with Cucumber (BDD)

Cypress Boilerplate with POM and Cucumber Download & Configuration npm init --> package.json npm install cypress cypress-cucumber-preprocessor --> pac

Sefa Batuhan Bayazitoğlu 7 Nov 4, 2022
Minimalistic, lean & mean, node.js cms

enduro.js Enduro is minimalistic, lean & mean, node.js cms. See more at enduro.js website Other repositories: Enduro • samples • Enduro admin • enduro

Martin Gottweis 688 Dec 31, 2022
Base62-token.js - Generate & Verify GitHub-style & npm-style Base62 Tokens

base62-token.js Generate & Verify GitHub-style & npm-style Secure Base62 Tokens Works in Vanilla JS (Browsers), Node.js, and Webpack. Online Demo See

Root 4 Jun 11, 2022
@TGMusicfy - Minimalistic Telegram music search bot written in TypeScript and based on Telegraf and Express JS.

@TGMusicfy Go to bot Deployed thanks to Heroku and New-Relic Bots are special Telegram accounts designed to handle messages automatically. Users can i

Saveliy Andronov 5 Sep 13, 2022
Minimalistic portfolio/photography site with masonry grid, page transitions and big images.

Gatsby Starter Portfolio: Emilia Minimalistic portfolio/photography site with masonry grid, page transitions and big images. Themeable with Theme UI.

Cryptob3auty 1 May 20, 2022
CalendarPickerJS - A minimalistic and modern date-picker component/library 🗓️👨🏽‍💻 Written in Vanilla JS

CalendarPickerJS The simple and pretty way to let a user select a day! Supports all major browser. Entirely written in Vanilla JavaScript with no depe

Mathias Picker 15 Dec 6, 2022
A minimalistic web application made using Next.js and Twitter API for Saturday Hack Night by TinkerHub

The Twittr. On the social media platform Twitter, a ratio, or getting ratioed, is when replies to a tweet vastly outnumber likes or retweets. This mea

Aswin Asok 5 Apr 17, 2022
A minimalistic area card with sensors and buttons.

Minimalistic Area Card A minimalistic area card to have a control panel of your house on your dashboard. This card will show numeric sensors with its

Marcos Junior 36 Jan 6, 2023
Minimalistic, opinionated, and predictable release automation tool.

Release Minimalistic, opinionated, and predictable release automation tool. General idea Think Prettier but for automated releases: minimalistic, opin

Open Source: JavaScript 173 Dec 18, 2022
A minimalistic card for Home Assistant Lovelace UI which shows how many days it has been between any input_datetime and today.

Datetime Card A minimalistic card for Home Assistant Lovelace UI which shows how many days it has been between any input_datetime and today. Useful to

Antonino Piazza 12 Aug 12, 2022