npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mocha-set-for-context

v1.0.0

Published

Test helper for mocha used to set object values for a describe block

Downloads

7

Readme

setForContext helper for Mocha

Set object values for a context.

Install

npm install mocha-set-for-context

You probably should also save it as a development dependency to your package.json

npm install --save-dev mocha-set-for-context

Usage

Use it in the body of a describe block to set values for an object or an array defined higher up in the tests to certain values.

var setForContext = require('mocha-set-for-context');

describe('My Tests', function () {
  var myObject = {foo: null};
  beforeEach(function () {
    console.log('Value of myObject.foo is ' + myObject.foo);
  });

  it('defaults foo to null', function () {
    if (myObject.foo !== null) throw new Error('foo was not null');
  });

  describe('when foo is bar', function () {
    setForContext(myObject, { foo: 'bar' });

    it('sets foo to bar', function () {
      if (myObject.foo !== 'bar') throw new Error('foo was not bar');
    });

    describe('and foobar is set to quz', function () {
      setForContext(myObject, { foobar: 'quz' });

      it('keeps foo as bar and sets foobar to quz', function () {
        if (myObject.foo !== 'bar') throw new Error('foo was not bar');
        if (myObject.foobar !== 'quz') throw new Error('foobar was not quz');
      });
    });
  });
});

If you need the values of the object to be calculated when the actual tests are ran, pass a function to the second parameter returning the values to be set. This is useful for setting Date values or using a value which is only available at the time when Mocha runs the actual describe block.

var myObject = { now: 0 };
describe('lazy evaluation', function () {
  setForContext(myObject, function () { return { now: Date.now() }});
  var testLoadedAt = Date.now();

  it('works', function () {
    if (testLoadedAt >= myObject.now) throw new Error("Oops.");
  });
});

setTimeout(mocha.run, 1000):
var myObject = { ref: null };
var someRef = null;

function setSomeRef() { someRef = 'Hello' };

describe('lazy evaluation', function () {
  setForContext(myObject, function () { return { ref: someRef }});
  setSomeRef();

  it('works', function () {
    if (myObject.ref !== someRef) throw new Error("Oops.");
  });
});

Why should I use it?

It might be a bit cumbersome to setup e.g. React component testing with plain Mocha. You might need to create some repetition when you want to test rendering based on different props, such as the one below:

describe('MyComponent', function () {
  describe('when foo is bar', function () {
    var component;
    beforeEach(function () {
      component = React.TestUtils.renderIntoDocument(MyComponent({foo: 'bar'}));
    });
    afterEach(function () {
      React.unmountComponentAtNode(reactElement.getDOMNode().parentNode);
    });

    it('renders Foobar', function () {
      // Will throw if not found
      React.TestUtils.findRenderedComponentWithType(component, Foobar);
    });
  });

  describe('when foo is not bar', function () {
    var component;
    beforeEach(function () {
      component = React.TestUtils.renderIntoDocument(MyComponent({foo: 'quz'}));
    });
    afterEach(function () {
      React.unmountComponentAtNode(reactElement.getDOMNode().parentNode);
    });

    it('does not render Foobar', function () {
      try {
        React.TestUtils.findRenderedComponentWithType(component, Foobar);
        throw new Error("Expected Foobar not to have been rendered but it was.");
      }
      catch () {}
    });
  });
});

So you end up duplicating some related test setup functionality. What if you could just define the rendering once and then just focus your tests on the rendered components?

Enter setForContext:

var setForContext = require('mocha-set-for-context');

describe('MyComponent', function () {
  var component;
  var props = {};
  beforeEach(function () {
      component = React.TestUtils.renderIntoDocument(MyComponent(props));
    });
    afterEach(function () {
      React.unmountComponentAtNode(component.getDOMNode().parentNode);
    });

  describe('when foo is bar', function () {
    setForContext(props, { foo: 'bar' });

    it('renders Foobar', function () {
      // Will throw if not found
      React.TestUtils.findRenderedComponentWithType(component, Foobar);
    });
  });

  describe('when foo is not bar', function () {
    setForContext(props, { foo: 'quz' });

    it('does not render Foobar', function () {
      try {
        React.TestUtils.findRenderedComponentWithType(component, Foobar);
        throw new Error('Expected Foobar not to have been rendered but it was.');
      }
      catch () {}
    });
  });
});

How it works?

setForContext works by setting the object/array values inside a describe block and then resetting those values after the describe block is finished by using a combination of before and after hooks in Mocha. As before hooks are always ran before beforeEach, you can setup object/array values used in a beforeEach block with setForContext. You don't have to worry about resetting those values as setForContext does it automatically for you.