• Stars
    star
    586
  • Rank 76,279 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 13 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Write Beautiful Specs with Custom Matchers for Jest and Jasmine

Jasmine-Matchers

Write Beautiful Specs with Custom Matchers

NPM version NPM downloads Build Status Maintainability

Table of Contents

Overview

What

A huge library of test matchers for a range of common use-cases, compatible with all versions of Jasmine and Jest.

Why

Custom Matchers make tests easier to read and produce relevant and useful messages when they fail.

How

By avoiding vague messages such as "expected false to be true" in favour of useful cues such as "expected 3 to be even number" and avoiding implementation noise such as expect(cycleWheels % 2 === 0).toEqual(true) in favour of simply stating that you expect(cycleWheels).toBeEvenNumber().

Sponsors
Sponsored by BrowserStack

🌩 Installation

npm
npm install jasmine-expect --save-dev
Bower
bower install jasmine-expect --save-dev
Manual

Downloads are available on the releases page.

πŸ“ API

The Jasmine testing framework from Pivotal Labs comes with this default set of matchers:

expect().nothing()
expect().toBe(expected)
expect().toBeCloseTo(expected, precisionopt)
expect().toBeDefined()
expect().toBeFalse()
expect().toBeFalsy()
expect().toBeGreaterThan(expected)
expect().toBeGreaterThanOrEqual(expected)
expect().toBeInstanceOf(expected)
expect().toBeLessThan(expected)
expect().toBeLessThanOrEqual(expected)
expect().toBeNaN()
expect().toBeNegativeInfinity()
expect().toBeNull()
expect().toBePositiveInfinity()
expect().toBeTrue()
expect().toBeTruthy()
expect().toBeUndefined()
expect().toContain(expected)
expect().toEqual(expected)
expect().toHaveBeenCalled()
expect().toHaveBeenCalledBefore(expected)
expect().toHaveBeenCalledOnceWith()
expect().toHaveBeenCalledTimes(expected)
expect().toHaveBeenCalledWith()
expect().toHaveClass(expected)
expect().toHaveSize(expected)
expect().toMatch(expected)
expect().toThrow(expectedopt)
expect().toThrowError(expectedopt, messageopt)
expect().toThrowMatching(predicate)
expect().withContext(message)

and this default set of asymmetric matchers;

jasmine.any(Constructor);
jasmine.anything(mixed);
jasmine.arrayContaining(mixed);
jasmine.objectContaining(mixed);
jasmine.stringMatching(pattern);

Matchers

Jasmine-Matchers adds the following matchers:

expect(array).toBeArray();
expect(array).toBeArrayOfBooleans();
expect(array).toBeArrayOfNumbers();
expect(array).toBeArrayOfObjects();
expect(array).toBeArrayOfSize(number);
expect(array).toBeArrayOfStrings();
expect(array).toBeEmptyArray();
expect(array).toBeNonEmptyArray();
expect(boolean).toBeBoolean();
expect(date).toBeAfter(otherDate);
expect(date).toBeBefore(otherDate);
expect(date).toBeDate();
expect(date).toBeValidDate();
expect(fn).toBeFunction();
expect(fn).toThrowAnyError();
expect(fn).toThrowErrorOfType(constructorName);
expect(mixed).toBeCalculable();
expect(number).toBeEvenNumber();
expect(number).toBeGreaterThanOrEqualTo(otherNumber);
expect(number).toBeLessThanOrEqualTo(otherNumber);
expect(number).toBeNear(otherNumber, epsilon);
expect(number).toBeNumber();
expect(number).toBeOddNumber();
expect(number).toBeWholeNumber();
expect(number).toBeWithinRange(floor, ceiling);
expect(object).toBeEmptyObject();
expect(object).toBeNonEmptyObject();
expect(object).toBeObject();
expect(object).toHaveArray(memberName);
expect(object).toHaveArrayOfBooleans(memberName);
expect(object).toHaveArrayOfNumbers(memberName);
expect(object).toHaveArrayOfObjects(memberName);
expect(object).toHaveArrayOfSize(memberName, size);
expect(object).toHaveArrayOfStrings(memberName);
expect(object).toHaveBoolean(memberName);
expect(object).toHaveCalculable(memberName);
expect(object).toHaveDate(memberName);
expect(object).toHaveDateAfter(memberName, date);
expect(object).toHaveDateBefore(memberName, date);
expect(object).toHaveEmptyArray(memberName);
expect(object).toHaveEmptyObject(memberName);
expect(object).toHaveEmptyString(memberName);
expect(object).toHaveEvenNumber(memberName);
expect(object).toHaveFalse(memberName);
expect(object).toHaveHtmlString(memberName);
expect(object).toHaveIso8601(memberName);
expect(object).toHaveJsonString(memberName);
expect(object).toHaveMember(memberName);
expect(object).toHaveMethod(memberName);
expect(object).toHaveNonEmptyArray(memberName);
expect(object).toHaveNonEmptyObject(memberName);
expect(object).toHaveNonEmptyString(memberName);
expect(object).toHaveNumber(memberName);
expect(object).toHaveNumberWithinRange(memberName, floor, ceiling);
expect(object).toHaveObject(memberName);
expect(object).toHaveOddNumber(memberName);
expect(object).toHaveString(memberName);
expect(object).toHaveStringLongerThan(memberName, string);
expect(object).toHaveStringSameLengthAs(memberName, string);
expect(object).toHaveStringShorterThan(memberName, string);
expect(object).toHaveTrue(memberName);
expect(object).toHaveUndefined(memberName);
expect(object).toHaveWhitespaceString(memberName);
expect(object).toHaveWholeNumber(memberName);
expect(regexp).toBeRegExp();
expect(string).toBeEmptyString();
expect(string).toBeHtmlString();
expect(string).toBeIso8601();
expect(string).toBeJsonString();
expect(string).toBeLongerThan(otherString);
expect(string).toBeNonEmptyString();
expect(string).toBeSameLengthAs(otherString);
expect(string).toBeShorterThan(otherString);
expect(string).toBeString();
expect(string).toBeWhitespace();
expect(string).toEndWith(substring);
expect(string).toStartWith(substring);

Asymmetric Matchers

any.after(date);
any.arrayOfBooleans();
any.arrayOfNumbers();
any.arrayOfObjects();
any.arrayOfSize(number);
any.arrayOfStrings();
any.before(date);
any.calculable();
any.emptyArray();
any.emptyObject();
any.endingWith(string);
any.evenNumber();
any.greaterThanOrEqualTo(number);
any.iso8601();
any.jsonString();
any.lessThanOrEqualTo(number);
any.longerThan(string);
any.nonEmptyArray();
any.nonEmptyObject();
any.nonEmptyString();
any.oddNumber();
any.regExp();
any.sameLengthAs(string);
any.shorterThan(string);
any.startingWith(string);
any.whitespace();
any.wholeNumber();
any.withinRange(floor, ceiling);

πŸ•Ή Usage

Browser

Embed jasmine-matchers.js after Jasmine but before your tests.

Jest

Include the following in your package.json:

"unmockedModulePathPatterns": ["jasmine-expect"]

And the following at the top of your test suite:

import JasmineExpect from "jasmine-expect";

Karma

Integration is easy with the karma-jasmine-matchers plugin.

Node.js

Use the Jasmine CLI and include the path to where Jasmine Matchers is installed in the helpers array of your spec/support/jasmine.json.

{
  "spec_dir": "spec",
  "spec_files": ["../src/**/*.spec.js"],
  "helpers": ["../node_modules/jasmine-expect/index.js"],
  "stopSpecOnExpectationFailure": false,
  "random": false
}

TypeScript and Angular CLI Projects

If you are using TypeScript, you might want to npm install @types/jasmine-expect --save-dev in order to prevent your IDE from complaining about the new Matchers.

Also, if you run into TypeScript compilation errors when running your tests, add "jasmine-expect" to the "types" array in your tests' tsconfig file.

As an example, for an Angular CLI based project, this would be your tsconfig.spec.json file:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "baseUrl": "./",
    "module": "commonjs",
    "target": "es5",
    "types": ["jasmine", "node", "jasmine-expect"]
  },
  "files": ["test.ts"],
  "include": ["**/*.spec.ts", "**/*.d.ts"]
}

Sublime Text

Jasmine-Matchers-Snippets or Jasmine-Matchers-ES6-Snippets can be installed with Package Control to ease development with Jasmine Matchers in Sublime Text.

Tern

There is a Plugin for Tern to auto-complete matchers in your Text Editor.

🌍 Browser Support

Jasmine-Matchers is tested on Travis CI and BrowserStack against the following environments.

Browser Version Range
Android 9 - 11
Chrome 80 - 85
Edge 80 - 85
Firefox 76 - 80
iOS 10 - 14
Safari 10 - 13

πŸ™‹πŸ½β€β™‚οΈ Getting Help

Get help with issues by creating a Bug Report or discuss ideas by opening a Feature Request.

πŸ‘€ Other Projects

If you find my Open Source projects useful, please share them ❀️

πŸ€“ Author

I'm Jamie Mason from Leeds in England, I began Web Design and Development in 1999 and have been Contracting and offering Consultancy as Fold Left Ltd since 2012. Who I've worked with includes Sky Sports, Sky Bet, Sky Poker, The Premier League, William Hill, Shell, Betfair, and Football Clubs including Leeds United, Spurs, West Ham, Arsenal, and more.

Follow JamieMason on GitHubΒ Β Β Β Β Β Follow fold_left on Twitter

More Repositories

1

ImageOptim-CLI

Make optimisation of images part of your automated build process
TypeScript
3,452
star
2

syncpack

Consistent dependency versions in large JavaScript Monorepos.
TypeScript
1,426
star
3

shrinkpack

Fast, resilient, reproducible builds with npm install.
TypeScript
793
star
4

grunt-imageoptim

Make ImageOptim, ImageAlpha and JPEGmini part of your automated build process
JavaScript
479
star
5

expect-more

Curried Type Testing library, and Test Matchers for Jest
TypeScript
172
star
6

astexplorer.app

An https://astexplorer.net wrapper which adds module bundling and hot reloading.
TypeScript
120
star
7

karma-benchmark

A Karma plugin to run Benchmark.js over multiple browsers with CI compatible output.
TypeScript
90
star
8

codemods

A collection of transforms for use with JSCodeshift
JavaScript
59
star
9

blurhash-to-css

Convert BlurHashes to CSS Objects using TypeScript, Rust, and WebAssembly.
TypeScript
56
star
10

eslint-plugin-prefer-arrow-functions

Auto-fix plain Functions into Arrow Functions, in all cases where conversion would result in the same behaviour
TypeScript
52
star
11

karma-jasmine-matchers

A Karma plugin to inject Jasmine-Matchers for Jasmine and Jest.
JavaScript
46
star
12

nextjs-typescript-tailwind-critical-css

Next.js 9.3 with TypeScript, tailwindcss, and inlined Critical CSS.
TypeScript
41
star
13

eslint-formatter-git-log

ESLint Formatter featuring Git Author, Date, and Hash
TypeScript
41
star
14

ts-import-types-cli

Autofix TypeScript types to be imported using `import type`
TypeScript
40
star
15

self-help

Interactive Q&A Guides for Web and the Command Line.
TypeScript
37
star
16

image-optimisation-tools-comparison

A Benchmarking Suite for popular Image Optimisation Tools
TypeScript
28
star
17

Unreadable

An intelligent/CSS-aware HTML Minifier and Optimizer
JavaScript
26
star
18

custom-linkedin-cv

LinkedIn profile JSON + AngularJS == Custom RΓ©sumΓ©
CSS
23
star
19

add-matchers

Write useful test matchers compatible with Jest and Jasmine.
JavaScript
18
star
20

syncpack-github-action

A GitHub Action to synchronise monorepo dependency versions with syncpack.
14
star
21

karma-nested-reporter

Easy to read test output with nested describe and it blocks
JavaScript
14
star
22

devtools-extension-tab-colours

Adds colours to the tabs in Chrome DevTools.
CSS
11
star
23

glob-bus

249 byte event emitter / pubsub with namespaced wildcards.
TypeScript
10
star
24

phantomjs-test-starter

A boilerplate / starter template for testing PhantomJS β€˜Applications’ with Jasmine, Grunt and Istanbul
JavaScript
8
star
25

eslint-plugin-move-files

Move and rename files while keeping imports up to date
TypeScript
8
star
26

logservable

git log as an observable stream of JSON
TypeScript
8
star
27

subclass.js

Inherit, extend, decorate, and override classes and instances.
JavaScript
7
star
28

Jasmine-Matchers-Snippets

Snippets for Jest & Jasmine Matchers.
6
star
29

react-xstate-pull-to-refresh

Created with CodeSandbox
TypeScript
6
star
30

giterator

`git log` as a JavaScript generator
TypeScript
5
star
31

grunt-rewrite

A Grunt plugin to edit & replace file contents.
JavaScript
5
star
32

conventional-recommended-version

Determine the semantic version number of your project
TypeScript
5
star
33

csslib

A customised fork of inuitcss which I use on most projects.
CSS
5
star
34

node-es6-starter

babel, code climate, commitizen, coveralls, easystatic, ghooks, istanbul, jasmine, rollup, travis, xo.
JavaScript
4
star
35

peach.js

A precompiled forEach, unrolled for faster runtime performance.
JavaScript
4
star
36

doei

Experiment: Remove unused CSS/JS using RUM Code Coverage
TypeScript
4
star
37

Tim

Node.js, Express & MongoDB app starter template with multi-language support, user registration and authentication
JavaScript
4
star
38

jest-fail-on-console-reporter

Disallow untested console output produced during tests
TypeScript
2
star
39

treeify

Format an indented text file in the style of the Linux tree command
JavaScript
2
star
40

valueless

Replace values with paths, for use in test fixtures
JavaScript
2
star
41

lastfm-to-itunes

JavaScript
2
star
42

generator-jekyll-inuit

A Jekyll Website with Inuit.css generator for Yeoman
CSS
2
star
43

shrinkpack-examples

Examples of monorepos using shrinkpack to install while offline.
2
star
44

get-time-between

Measure the amount of time during work hours between two dates
TypeScript
2
star
45

is-office-hours

Determine whether a given date is within office hours
TypeScript
2
star
46

Jasmine-Matchers-ES6-Snippets

ES6 Snippets for Jest & Jasmine Matchers.
2
star
47

next-optimized-head

Next.js `<Head/>` which orders elements to improve (perceived) page performance.
TypeScript
2
star
48

commit-release

Commit and tag a conventional changelog release
TypeScript
1
star
49

front-end-engineer-interview-exercise

How do other Developers approach interview exercises?
1
star
50

github-actions-temporary-repo

JavaScript
1
star