diff --git a/README.md b/README.md index 88b15a2..4b18d57 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ extendable utilities for testing - [Usage](#usage) * [Stub](#stub) * [Catch](#catch) + * [Finally](#finally) * [Nock](#nock) * [Environment Variables](#environment-variables) * [Run](#run) @@ -143,6 +144,20 @@ it('dont do this', () => { But this has a common flaw, if the test does not error, the test will still pass. Chai and other assertion libraries have helpers for this, but they still end up with somewhat messy code. +Finally +------- + +Run a tasks even if the test errors out. + +```js +describe('finally tests', () => { + fancy + .do(() => { throw new Error('x') }) + .finally(() => { /* always called */ }) + .end('always calls finally') +}) +``` + Nock ---- diff --git a/src/base.ts b/src/base.ts index cf4d2c0..a8c792a 100644 --- a/src/base.ts +++ b/src/base.ts @@ -82,6 +82,12 @@ const base = (context: I): Types.Base => { chain: [...context.chain, {run: (input: any) => cb(input)}] }) }, + finally(cb) { + return base({ + ...context as any, + chain: [...context.chain, {finally: (input: any) => cb(input)}] + }) + }, add(key, cb) { return base({ ...context as any, diff --git a/src/types.ts b/src/types.ts index 8450336..989c58c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -36,6 +36,7 @@ export type Base = { } add(key: K, cb: (context: I) => Promise | O): Base do(cb: (context: I & O) => any): Base + finally(cb: (context: I) => any): Base register(key: K, plugin: (arg1?: A1, arg2?: A2, arg3?: A3, arg4?: A4) => Plugin): Base } & {[P in keyof T]: (arg1?: T[P]['a1'], arg2?: T[P]['a2'], arg3?: T[P]['a3'], arg4?: T[P]['a4']) => Base} diff --git a/test/finally.test.ts b/test/finally.test.ts new file mode 100644 index 0000000..19911aa --- /dev/null +++ b/test/finally.test.ts @@ -0,0 +1,17 @@ +// tslint:disable no-console + +import {fancy} from '../src' + +describe('finally', () => { + // from readme + // fancy + // .do(() => { throw new Error('x') }) + // .finally(() => console.log('foo')) + // .end('always calls finally') + // from readme + + fancy + // not sure how to actually test this + .finally(() => {}) + .end('finally') +})