Convert Figma logo to code with AI

mjackson logoexpect

Write better assertions

2,288
117
2,288
11

Top Related Projects

Additional Jest matchers 🃏💪

8,106

BDD / TDD assertion framework for node.js and the browser that can be paired with any testing framework.

15,728

Simple JavaScript testing framework for browsers and node.js

BDD style assertions for node.js -- test framework agnostic

44,045

Delightful JavaScript Testing.

Quick Overview

The mjackson/expect project is a JavaScript assertion library that provides a more readable and expressive syntax for writing tests. It is designed to work with any testing framework, making it a versatile tool for developers who want to write more readable and maintainable tests.

Pros

  • Readable Assertions: The library provides a fluent, readable syntax for writing assertions, making it easier to understand what is being tested.
  • Extensibility: Developers can extend the library with custom matchers, allowing them to create domain-specific assertions.
  • Cross-Framework Compatibility: The library can be used with a variety of testing frameworks, including Jest, Mocha, and Jasmine.
  • Comprehensive Assertions: The library provides a wide range of built-in assertions, covering common use cases.

Cons

  • Learning Curve: The library's fluent syntax may require some initial learning for developers who are used to more traditional assertion styles.
  • Dependency on Other Libraries: The library relies on other libraries, such as is-regex and is-equal, which may introduce additional dependencies in a project.
  • Limited Browser Support: The library is primarily designed for use in Node.js environments and may have limited support for older browsers.
  • Potential Performance Impact: The library's extensive assertion capabilities may have a slight performance impact on large test suites.

Code Examples

Here are a few examples of how to use the mjackson/expect library:

import expect from 'expect';

// Asserting that a value is truthy
expect(true).toBe(true);
expect(1).toExist();
expect([]).toNotBeEmpty();

// Asserting that a value is falsy
expect(false).toBeFalsy();
expect(0).toNotExist();
expect({}).toBeEmpty();

// Asserting that a value matches a regular expression
expect('hello world').toMatch(/hello/);
expect('foo@example.com').toMatch(/\S+@\S+\.\S+/);

// Asserting that a function throws an error
expect(() => {
  throw new Error('Something went wrong');
}).toThrow();

Getting Started

To get started with the mjackson/expect library, follow these steps:

  1. Install the library using npm or yarn:
npm install expect
  1. Import the expect function in your test file:
import expect from 'expect';
  1. Use the expect function to write your assertions:
test('addition', () => {
  expect(1 + 1).toBe(2);
  expect(3 - 1).toNotBe(2);
});
  1. Customize your assertions by using the library's built-in matchers or creating your own:
expect.extend({
  toBePositive(received) {
    const pass = received > 0;
    if (pass) {
      return {
        message: () => `expected ${received} to be positive`,
        pass: true
      };
    } else {
      return {
        message: () => `expected ${received} to be positive`,
        pass: false
      };
    }
  }
});

test('custom matcher', () => {
  expect(5).toBePositive();
  expect(-3).toNotBePositive();
});

By following these steps, you can start using the mjackson/expect library to write more readable and maintainable tests in your JavaScript projects.

Competitor Comparisons

Additional Jest matchers 🃏💪

Pros of jest-extended

  • Extends Jest's built-in matchers, providing a more comprehensive set of assertions
  • Seamlessly integrates with existing Jest setups, requiring minimal configuration
  • Actively maintained with regular updates and community support

Cons of jest-extended

  • Larger package size due to additional matchers and functionality
  • May introduce a slight learning curve for developers unfamiliar with the extended matchers
  • Potential for conflicts with other Jest plugins or custom matchers

Code Comparison

expect:

expect(value).toBe(expected);
expect(value).toEqual(expected);
expect(value).toBeGreaterThan(expected);

jest-extended:

expect(value).toBe(expected);
expect(value).toEqual(expected);
expect(value).toBeGreaterThan(expected);
expect(value).toBeWithin(start, end);
expect(value).toBeArrayOfSize(size);

Summary

jest-extended builds upon Jest's functionality, offering a wider range of matchers and assertions. It's ideal for projects already using Jest and requiring more advanced testing capabilities. expect, on the other hand, is a standalone assertion library that can be used independently or with various testing frameworks. While jest-extended provides more out-of-the-box functionality, expect offers greater flexibility and lighter weight for projects not specifically tied to Jest.

8,106

BDD / TDD assertion framework for node.js and the browser that can be paired with any testing framework.

Pros of Chai

  • More extensive and flexible assertion library with multiple styles (expect, should, assert)
  • Larger ecosystem with plugins and extensions
  • Better suited for complex testing scenarios and diverse project requirements

Cons of Chai

  • Steeper learning curve due to multiple assertion styles and extensive API
  • Slightly more verbose syntax in some cases
  • Larger package size, which may impact load times in certain environments

Code Comparison

Chai:

expect(foo).to.be.a('string');
expect(foo).to.equal('bar');
expect(foo).to.have.lengthOf(3);

Expect:

expect(foo).toBeA('string');
expect(foo).toBe('bar');
expect(foo).toHaveLength(3);

Both libraries offer similar functionality for basic assertions, but Chai provides more flexibility in syntax and assertion styles. Expect focuses on a simpler, more straightforward API with a smaller footprint. While Chai is more feature-rich and adaptable to various testing needs, Expect offers a more streamlined experience with a gentler learning curve. The choice between the two often depends on project requirements, team preferences, and the complexity of the testing scenarios.

15,728

Simple JavaScript testing framework for browsers and node.js

Pros of Jasmine

  • More comprehensive testing framework with built-in test runner
  • Extensive documentation and large community support
  • Supports both browser and Node.js environments out of the box

Cons of Jasmine

  • Steeper learning curve due to more features and complexity
  • Heavier and more opinionated compared to lightweight assertion libraries
  • Setup can be more time-consuming for simple projects

Code Comparison

Jasmine:

describe("Calculator", function() {
  it("should add numbers", function() {
    expect(add(1, 2)).toBe(3);
  });
});

Expect:

test("adding numbers", () => {
  expect(add(1, 2)).toBe(3);
});

Key Differences

  • Expect is a lightweight assertion library, while Jasmine is a full-featured testing framework
  • Jasmine provides a complete testing environment, whereas Expect focuses solely on assertions
  • Expect offers a more flexible and extensible API for custom matchers
  • Jasmine includes built-in mocking and spying capabilities, which Expect does not provide

Use Cases

  • Choose Jasmine for comprehensive testing needs in larger projects
  • Opt for Expect when you need a simple assertion library to integrate with other testing tools
  • Jasmine is well-suited for teams familiar with BDD-style testing
  • Expect is ideal for developers who prefer a minimalist approach and want to mix-and-match testing tools

BDD style assertions for node.js -- test framework agnostic

Pros of should.js

  • More extensive and expressive API with a wide range of assertions
  • Supports both BDD and TDD styles of testing
  • Allows for easy chaining of assertions

Cons of should.js

  • Larger library size compared to expect
  • May have a steeper learning curve due to its extensive API
  • Less actively maintained (last update was in 2021)

Code Comparison

expect:

expect(value).toBe(expected);
expect(value).toEqual(expected);
expect(value).toBeGreaterThan(expected);

should.js:

value.should.equal(expected);
value.should.eql(expected);
value.should.be.above(expected);

Key Differences

  • Syntax: expect uses a function-based approach, while should.js extends Object.prototype
  • Assertion style: expect focuses on a more concise, straightforward syntax, while should.js aims for a more natural language-like approach
  • Community and ecosystem: expect is part of the Jest testing framework, which has a larger community and more frequent updates

Use Cases

  • expect: Ideal for projects using Jest or those preferring a more lightweight assertion library
  • should.js: Better suited for projects requiring a rich set of assertions and preferring a BDD-style syntax

Both libraries serve similar purposes but cater to different preferences in testing styles and ecosystem integration.

44,045

Delightful JavaScript Testing.

Pros of Jest

  • Comprehensive testing framework with built-in test runner, assertion library, and mocking capabilities
  • Extensive documentation and large community support
  • Snapshot testing feature for UI components

Cons of Jest

  • Larger package size and potentially slower setup time
  • Steeper learning curve for beginners due to more features
  • May be overkill for small projects or simple testing needs

Code Comparison

expect:

import expect from 'expect';

expect(2 + 2).toBe(4);
expect({ a: 1 }).toEqual({ a: 1 });
expect([1, 2, 3]).toContain(2);

Jest:

test('addition', () => {
  expect(2 + 2).toBe(4);
  expect({ a: 1 }).toEqual({ a: 1 });
  expect([1, 2, 3]).toContain(2);
});

Summary

expect is a lightweight assertion library that focuses on providing a simple and intuitive API for writing test assertions. It's ideal for projects that require a minimal testing setup or want to use a custom test runner.

Jest, on the other hand, is a full-featured testing framework that includes expect as its assertion library. It offers a complete testing solution with additional features like test runners, mocking, and code coverage. Jest is well-suited for larger projects or those requiring a more comprehensive testing environment.

The choice between expect and Jest depends on the project's specific needs, size, and complexity. expect is more flexible and can be integrated with various test runners, while Jest provides an all-in-one solution for JavaScript testing.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

expect Travis npm package

Notice

This package has been donated to Jest. This means that all future development of expect v21+ will take place at facebook/jest.

You can use jest-codemods to automatically migrate your old tests using expect@1.x to the new jest version of expect (>= 21)

Versions prior to v21 will receive limited support and bugfixes, and any future < v21 releases will be published on an npm tag that is not "latest", to avoid causing problems for v21+ users.

expect@1.x documentation

expect lets you write better assertions.

When you use expect, you write assertions similarly to how you would say them, e.g. "I expect this value to be equal to 3" or "I expect this array to contain 3". When you write assertions in this way, you don't need to remember the order of actual and expected arguments to functions like assert.equal, which helps you write better tests.

You can think of expect as a more compact alternative to Chai or Sinon.JS, just without the pretty website. ;)

Installation

Using npm:

$ npm install --save expect

Then, use as you would anything else:

// using ES6 modules
import expect, { createSpy, spyOn, isSpy } from 'expect'

// using CommonJS modules
var expect = require('expect')
var createSpy = expect.createSpy
var spyOn = expect.spyOn
var isSpy = expect.isSpy

The UMD build is also available on unpkg:

<script src="https://unpkg.com/expect@%3C21/umd/expect.min.js"></script>

You can find the library on window.expect.

Assertions

toExist

expect(object).toExist([message])

Asserts the given object is truthy.

expect('something truthy').toExist()

Aliases:

  • toBeTruthy

toNotExist

expect(object).toNotExist([message])

Asserts the given object is falsy.

expect(null).toNotExist()

Aliases:

  • toBeFalsy

toBe

expect(object).toBe(value, [message])

Asserts that object is strictly equal to value using ===.

toNotBe

expect(object).toNotBe(value, [message])

Asserts that object is not strictly equal to value using ===.

toEqual

expect(object).toEqual(value, [message])

Asserts that the given object equals value using is-equal.

toNotEqual

expect(object).toNotEqual(value, [message])

Asserts that the given object is not equal to value using is-equal.

toThrow

expect(block).toThrow([error], [message])

Asserts that the given block throws an error. The error argument may be a constructor (to test using instanceof), or a string/RegExp to test against error.message.

expect(function () {
  throw new Error('boom!')
}).toThrow(/boom/)

toNotThrow

expect(block).toNotThrow([message])

Asserts that the given block does not throw.

toBeA(constructor)

expect(object).toBeA(constructor, [message])
expect(object).toBeAn(constructor, [message])

Asserts the given object is an instanceof constructor.

expect(new User).toBeA(User)
expect(new Asset).toBeAn(Asset)

Aliases:

  • toBeAn

toBeA(string)

expect(object).toBeA(string, [message])
expect(object).toBeAn(string, [message])

Asserts the typeof the given object is string.

expect(2).toBeA('number')

Aliases:

  • toBeAn

toNotBeA(constructor)

expect(object).toNotBeA(constructor, [message])
expect(object).toNotBeAn(constructor, [message])

Asserts the given object is not an instanceof constructor.

expect(new Asset).toNotBeA(User)
expect(new User).toNotBeAn(Asset)

Aliases:

  • toNotBeAn

toNotBeA(string)

expect(object).toNotBeA(string, [message])
expect(object).toNotBeAn(string, [message])

Asserts the typeof the given object is not string.

expect('a string').toNotBeA('number')
expect(2).toNotBeAn('object')

Aliases:

  • toNotBeAn

toMatch

expect(string).toMatch(pattern, [message])
expect(object).toMatch(pattern, [message])

Asserts the given string or object matches a pattern. When using a string, pattern must be a RegExp. When using an object, pattern may be anything acceptable to tmatch.

expect('a string').toMatch(/string/)
expect({
  statusCode: 200,
  headers: {
    server: 'nginx/1.6.5'
  }
}).toMatch({
  headers: {
    server: /nginx/
  }
})

toNotMatch

expect(string).toNotMatch(pattern, [message])
expect(object).toNotMatch(pattern, [message])

Asserts the given string or object does not match a pattern. When using a string, pattern must be a RegExp. When using an object, pattern may be anything acceptable to tmatch.

expect('a string').toMatch(/string/)
expect({
  statusCode: 200,
  headers: {
    server: 'nginx/1.6.5'
  }
}).toNotMatch({
  headers: {
    server: /apache/
  }
})

toBeLessThan

expect(number).toBeLessThan(value, [message])
expect(number).toBeFewerThan(value, [message])

Asserts the given number is less than value.

expect(2).toBeLessThan(3)

Aliases:

  • toBeFewerThan

toBeLessThanOrEqualTo

expect(number).toBeLessThanOrEqualTo(value, [message])

Asserts the given number is less than or equal to value.

expect(2).toBeLessThanOrEqualTo(3)

toBeGreaterThan

expect(number).toBeGreaterThan(value, [message])
expect(number).toBeMoreThan(value, [message])

Asserts the given number is greater than value.

expect(3).toBeGreaterThan(2)

Aliases:

  • toBeMoreThan

toBeGreaterThanOrEqualTo

expect(number).toBeGreaterThanOrEqualTo(value, [message])

Asserts the given number is greater than or equal to value.

expect(3).toBeGreaterThanOrEqualTo(2)

toInclude

expect(array).toInclude(value, [comparator], [message])
expect(object).toInclude(value, [comparator], [message])
expect(string).toInclude(value, [message])

Asserts that a given value is included (or "contained") within another. The actual value may be an array, object, or a string. The comparator function, if given, should compare two objects and return false if they are not equal. The default is to use isEqual.

expect([ 1, 2, 3 ]).toInclude(3)
expect({ a: 1, b: 2 }).toInclude({ b: 2 })
expect({ a: 1, b: 2, c: { d: 3 } }).toInclude({ b: 2, c: { d: 3 } })
expect('hello world').toInclude('world')

Aliases:

  • toContain

toExclude

expect(array).toExclude(value, [comparator], [message])
expect(object).toExclude(value, [comparator], [message])
expect(string).toExclude(value, [message])

Asserts that a given value is not included (or "contained") within another. The actual value may be an array, object, or a string. The comparator function, if given, should compare two objects and return false if they are not equal. The default is to use isEqual.

expect([ 1, 2, 3 ]).toExclude(4)
expect({ a: 1, b: 2 }).toExclude({ c: 2 })
expect({ a: 1, b: 2 }).toExclude({ b: 3 })
expect({ a: 1, b: 2, c: { d: 3 } }).toExclude({ c: { d: 4 } })
expect('hello world').toExclude('goodbye')

Aliases:

  • toNotContain
  • toNotInclude

toIncludeKey(s)

expect(object).toIncludeKeys(keys, [comparator], [message])
expect(object).toIncludeKey(key, [comparator], [message])

Asserts that the given object (may be an array, or a function, or anything with keys) contains all of the provided keys. The optional parameter comparator is a function which if given an object and a string key, it should return a boolean detailing whether or not the key exists in the object. By default, a shallow check with Object.prototype.hasOwnProperty is performed.

expect({ a: 1 }).toIncludeKey('a')
expect({ a: 1, b: 2 }).toIncludeKeys([ 'a', 'b' ])

Aliases:

  • toContainKey(s)

toExcludeKey(s)

expect(object).toExcludeKeys(keys, [comparator], [message])
expect(object).toExcludeKey(key, [comparator], [message])

Asserts that the given object (may be an array, or a function, or anything with keys) does not contain any of the provided keys. The optional parameter comparator is a function which if given an object and a string key, it should return a boolean detailing whether or not the key exists in the object. By default, a shallow check with Object.prototype.hasOwnProperty is performed.

expect({ a: 1 }).toExcludeKey('b')
expect({ a: 1, b: 2 }).toExcludeKeys([ 'c', 'd' ])

Aliases:

  • toNotContainKey(s)
  • toNotIncludeKey(s)

(spy) toHaveBeenCalled

expect(spy).toHaveBeenCalled([message])

Asserts the given spy function has been called at least once.

expect(spy).toHaveBeenCalled()

(spy) toNotHaveBeenCalled

expect(spy).toNotHaveBeenCalled([message])

Asserts the given spy function has not been called.

expect(spy).toNotHaveBeenCalled()

(spy) toHaveBeenCalledWith

expect(spy).toHaveBeenCalledWith(...args)

Asserts the given spy function has been called with the expected arguments.

expect(spy).toHaveBeenCalledWith('foo', 'bar')

Chaining Assertions

Every assertion returns an Expectation object, so you can chain assertions together.

expect(3.14)
  .toExist()
  .toBeLessThan(4)
  .toBeGreaterThan(3)

Spies

expect also includes the ability to create spy functions that can track the calls that are made to other functions and make various assertions based on the arguments and context that were used.

var video = {
  play: function () {},
  pause: function () {},
  rewind: function () {}
}

var spy = expect.spyOn(video, 'play')

video.play('some', 'args')

expect(spy.calls.length).toEqual(1)
expect(spy.calls[0].context).toBe(video)
expect(spy.calls[0].arguments).toEqual([ 'some', 'args' ])
expect(spy).toHaveBeenCalled()
expect(spy).toHaveBeenCalledWith('some', 'args')

spy.restore()
expect.restoreSpies()

createSpy

expect.createSpy([fn], [restore])

Creates a spy function with an (optional) implementation and (optional) restore logic. (In order for your provided implementation to be used, you must call andCallThrough.) For this reason, it's better to use andCall if you don't need custom restore logic.

var spy = expect.createSpy()

spyOn

expect.spyOn(target, method)

Replaces the method in target with a spy.

var video = {
  play: function () {}
}

var spy = expect.spyOn(video, 'play')
video.play()

spy.restore()

restoreSpies

expect.restoreSpies()

Restores all spies created with expect.spyOn(). This is the same as calling spy.restore() on all spies created.

// mocha.js example
beforeEach(function () {
  expect.spyOn(profile, 'load')
})

afterEach(function () {
  expect.restoreSpies()
})

it('works', function () {
  profile.load()
  expect(profile.load).toHaveBeenCalled()
})

Spy methods and properties

andCall

spy.andCall(fn)

Makes the spy invoke a function fn when called.

var dice = createSpy().andCall(function () {
  return (Math.random() * 6) | 0
})

andCallThrough

spy.andCallThrough()

Makes the spy call the original function it's spying on.

spyOn(profile, 'load').andCallThrough()

var getEmail = createSpy(function () {
  return "hi@gmail.com"
}).andCallThrough()

andReturn

spy.andReturn(object)

Makes the spy return a value.

var dice = expect.createSpy().andReturn(3)

andThrow

spy.andThrow(error)

Makes the spy throw an error when called.

var failing = expect.createSpy()
  .andThrow(new Error('Not working'))

restore

spy.restore()

Restores a spy originally created with expect.spyOn().

reset

spy.reset()

Clears out all saved calls to the spy.

calls

spy.calls

An array of objects representing all saved calls to the spy.

You can use the length of the calls array to make assertions about how many times you expect the spy to have been called.

expect(spy.calls.length).toEqual(3)

You can also use the array to make assertions about each individual call. Each call object contains the following properties:

context

spy.calls[index].context

The this value of the call's execution context.

arguments

spy.calls[index].arguments

An array of the arguments passed to the spy for the particular call.

Extending expect

You can add your own assertions using expect.extend and expect.assert:

expect.extend({
  toBeAColor() {
    expect.assert(
      this.actual.match(/^#[a-fA-F0-9]{3,6}$/),
      'expected %s to be an HTML color',
      this.actual
    )
    return this
  }
})

expect('#ff00ff').toBeAColor()

Extensions

  • expect-element Adds assertions that are useful for DOM elements
  • expect-jsx Adds things like expect(ReactComponent).toEqualJSX(<TestComponent prop="yes" />)
  • expect-predicate Adds assertions based on arbitrary predicates
  • expect-enzyme Augments and extends expect to supercharge your enzyme assertions

NPM DownloadsLast 30 Days