diff --git a/README.md b/README.md index bb7b878..8b876cc 100644 --- a/README.md +++ b/README.md @@ -382,6 +382,20 @@ var failing = expect.createSpy() Restores a spy originally created with `expect.spyOn()`. +## Extending expect + +To create new expectations, add functions to `expect.fn` and call `expect.assert`. + +```js +expect.fn.toBeAColor = function () { + expect.assert(this.actual.match(/^#[a-fA-F0-9]{6}$/), + 'expected %s to be an HTML color', + this.actual) +} + +expect('#ff00ff').toBeAColor() +``` + ## Issues Please file issues on the [issue tracker on GitHub](https://github.com/mjackson/expect/issues). diff --git a/modules/__tests__/extension-test.js b/modules/__tests__/extension-test.js new file mode 100644 index 0000000..3819fe1 --- /dev/null +++ b/modules/__tests__/extension-test.js @@ -0,0 +1,23 @@ +/*eslint-env mocha */ +import expect from '../index' + +describe('expect.fn', function () { + beforeEach(function () { + expect.spyOn(expect, 'assert') + expect.fn.toBeAColor = function () { + expect.assert(this.actual.match(/^#[a-fA-F0-9]{6}$/), + 'expected %s to be an HTML color', + this.actual) + } + }) + + afterEach(function () { + expect.assert.restore() + delete expect.fn.toBeAColor + }) + + it('works', function () { + expect('#ff00ff').toBeAColor() + expect(expect.assert).toHaveBeenCalled() + }) +}) diff --git a/modules/index.js b/modules/index.js index b9bd720..0f48336 100644 --- a/modules/index.js +++ b/modules/index.js @@ -1,5 +1,6 @@ import Expectation from './Expectation' import { createSpy, spyOn, isSpy, restoreSpies } from './SpyUtils' +import invariant from './invariant' function expect(actual) { return new Expectation(actual) @@ -9,5 +10,7 @@ expect.createSpy = createSpy expect.spyOn = spyOn expect.isSpy = isSpy expect.restoreSpies = restoreSpies +expect.fn = Expectation.prototype +expect.assert = invariant export default expect