Code Monkey home page Code Monkey logo

mocha-wrap's Introduction

❗ Deprecation Notice
We want to express our sincere gratitude for your support and contributions to this open source project. As we are no longer using this technology internally, we have come to the decision to archive this repository. While we won't be providing further updates or support, the existing code and resources will remain accessible for your reference. We encourage anyone interested to fork the repository and continue the project's legacy independently. Thank you for being a part of this journey and for your patience and understanding.

mocha-wrap Version Badge

Build Status dependency status dev dependency status License Downloads

npm badge

Fluent pluggable interface for easily wrapping describe, context, it, and specify blocks in Mocha tests.

Example

var wrap = require('mocha-wrap');
var expect = require('chai').expect;

var mockWindow = {
	location: {
		href: 'test/url'
	}
};
wrap().withGlobal('window', () => mockWindow).describe('mocked window', function () {
	it('is mocked', function () {
		expect(window).to.equal(mockWindow);
	});

	it('has the right URL', function () {
		expect(window.location.href).to.equal('test/url');
	});
});

var obj = { a: 1 };
wrap().withOverrides(() => obj, () => ({ a: 2, b: 3 })).describe('overridden object keys', function () {
	it('has "b"', function () {
		expect(obj.b).to.equal(3);
	});

	it('has overridden "a"', function () {
		expect(obj.a).to.equal(2);
	});
});

wrap().withOverride(() => obj, 'a', () => 4).skip().describe('this test is skipped', function () {
	it('also supports .only()!', function () {
		expect(true).to.equal(false); // skipped
	});
});

Plugins

A mocha-wrap plugin is a named function that returns a MochaWrapper instance or a descriptor object.

  • A plugin’s function name must begin with the string “with”.

  • Plugins can be globally registered, or .used ad-hoc.

  • .use requires a plugin function as its first argument; further arguments are passed through to the plugin.

  • .extend requires a non-empty description string, and a descriptor object which may contain a value that is a function, or an array of functions, whose keys correspond to any or all of the supported mocha methods.

  • Globally registered plugins, .use calls, and .extend calls can be chained, stored, and reused - each link in the chain creates a new instance of a MochaWrapper.

  • A descriptor object may contain any or all of these 5 keys:

  • a description string, for use in “describe” and/or “it” (this is required when returning an object)

  • beforeEach: a function, or array of functions, for use in a mocha beforeEach function

  • afterEach: a function, or array of functions, for use in a mocha afterEach function

  • before: a function, or array of functions, for use in a mocha before function

  • after: a function, or array of functions, for use in a mocha after function

The most common approach will be for a plugin function to return this.extend(description, descriptor).

A plugin function must have a name that starts with “with”, and will be invoked with a receiver (”this” value) of a MochaWrapper instance.

To register a plugin, call the register function on mocha-wrap with the plugin function. This should not be done in a reusable module.

module.exports = function withFoo(any, args, you, want) {
	return this.extend('with some foo stuff', {
		beforeEach: function () {
			// setup ran before each test
		},
		afterEach: [
			function () {
				// teardown ran after each test
			},
			function () {
				// more teardown
			}
		],
		before: function () {
			// setup ran once before all tests
		},
		after: function () {
			// teardown ran once after all tests
		}
	});
};

Usage

var wrap = require('mocha-wrap');
wrap.register(require('mocha-wrap-with-foo'));

wrap().withFoo().describe…

skip/only

Although mocha has describe.skip, describe.only, context.skip, context.only, it.skip, it.only, specify.skip, and specify.only, it is not possible to implement these in mocha-wrap without using ES5 property accessors. Since this project supports ES3, we decided to use .skip().describe etc rather than forfeit the ability to have skip/only.

Tests

Simply clone the repo, npm install, and run npm test

mocha-wrap's People

Contributors

danbeam avatar gdborton avatar iancmyers avatar lencioni avatar ljharb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mocha-wrap's Issues

Make sure nested before/afters run in the right order

wrap().withFoo().withBar() should run foo's before/beforeEach's, then bar's before/beforeEach's, then the test, then bar's after/afterEach's, then foo'd after/afterEach's.

This will require tests, and will likely require a tweak in createAssertion

Mocha 4.0.0 support?

Would be good to have. Not sure if any changes are necessary beyond the peer dep bump.

TypeScript support

Hi,

Any chance to have TypeScript support ?

I would like to use it in my ts projects, but I didn't find any type definitions nor dedicated ts module for mocha-wrap.

Thx

withOverrides and objects

I just ran into this quirk while using withOverrides. I wanted to override the value of something with an object, e.g.:

.use(withOverrides, SOMETHING[foo], { BAR: bar })

but I sometimes ran into errors like:

 TypeError: Cannot convert undefined or null to object
at hasOwnProperty (native)
at binder (node_modules/function-bind/index.js:24:27)
at eval (<anonymous>:3:37)
at node_modules/mocha-wrap/withOverrides.js:18:9
at forEachArray (node_modules/mocha-wrap/node_modules/for-each/index.js:28:22)
at forEach (node_modules/mocha-wrap/node_modules/for-each/index.js:18:9)
at Context.beforeEachWithOverrides (node_modules/mocha-wrap/withOverrides.js:15:4)

and

 TypeError: Cannot convert undefined or null to object
at node_modules/mocha-wrap/withOverrides.js:41:20
at forEachArray (node_modules/mocha-wrap/node_modules/for-each/index.js:28:22)
at forEach (node_modules/mocha-wrap/node_modules/for-each/index.js:18:9)
at Context.afterEachWithOverrides (node_modules/mocha-wrap/withOverrides.js:31:4)

To resolve this, I modified my code to move some things around like:

const overrides = {
  [foo]: { BAR: bar },
};
...
.use(withOverrides, SOMETHING, overrides)

Intimidating code...

While digging into #24, it took me a long time to understand what was going on in the codebase, and then took me even longer to understand why.

After trying to grok the code for longer than I'd like to admit, I can see that...

This code:

return setThisDescription(concatThis(this, newWrappers), description);

is essentially a different way of doing this:

return new MochaWrapper({
  wrappers: newWrappers,
  description,
});

And that because of attempts to maintain privacy this...

return someChainableFunction(someOtherChainableFunction(myInstance));

was basically the same as this...

return this.someOtherChainableFunction().someChainableFunction();

My question is... would you be ok with:

  1. Changing the functional code to be more object oriented (we're passing instance a lot)
  2. Removing the attempts at maintaining privacy

^ I think that doing these would help to make the code much more approachable.

We could be explicit in that the internal functions/parameters are not part of the api, and will break without breaking changes.

Find a way to make `withGlobal`/`withOverride` take a thunk

Basically, sometimes you don't want to mock something with a singleton value - you might want the value to be determined based on the environment at the time of mocking: something like:

wrap()
  .withWindow(mockWindow)
  .withOverrides(function () { return window }, { location: { href: '#' } }))`)

Wrapping multiple things exponentially adds hooks.

Registering multiple wrappers makes each wrapper's hooks run an exponential amount of times.

For example:

const wrap = require('mocha-wrap');

var calls = 0;
function withFunk() {
  return this.extend('(with funk)', {
    beforeEach: () => {
      calls++;
      console.log(calls); // There is only one test, this should only be called 1 time.
    }
  });
}

function withOtherFunk() {
  return this.extend('(with other funk)', { /* fancy noop */ });
}

wrap.register(withFunk);
wrap.register(withOtherFunk);

wrap()
.withFunk()
.withOtherFunk()
.withOtherFunk()
.withOtherFunk()
.describe('something', () => {
  it('should pass', () => {});
});

Outputs:

~/code/mocha-wrap-test
❯ mocha                 


  wrapped: (with funk); (with other funk); (with other funk); (with other funk):
    something
1
2
3
4
5
6
7
8
      ✓ should pass


  1 passing (7ms)

@iancmyers ^ this is probably contributing to our memory pressure and test run time. Likely also test flakiness as we're setting up jsdom multiple times before tearing down.

Explore converting to babel

This project intentionally did not use babel because it has multiple top-level entry points.

Now that it's inside airbnb, it should switch to babel-preset-airbnb and eslint-config-airbnb-base, but I need to figure out how to make the build/cleanup/npmignore/gitignore process robust first.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.