Handle React's contenteditable warning in Jest

In complement to , here is a quick note regarding the warning thrown by React when using contenteditable on children elements of a component.

Although it does not seem to be going anywhere, you can silence it in a somewhat hacky way in Jest by doing the following :

console.warn = jest.genMockFunction();

Here is the issue I opened on GitHub on the subject, where I have been told some work would be put into making this particular warning less of a pain in the testsuite. Go on and leave a comment there if it annoys you as well !

Mock your React components with Jest

Unit testing of React components has been made possible by the folks over at Facebook in the form of Jest, a JavaScript test framework built on top of Jasmine. Despite a lack of maturity on some aspects at the current time, the tool proves itself useful overall. This article is meant to help you (and future me) avoid some pitfalls I encountered when getting started with it, especially regarding the use of mocks.

First things first, let's install Jest :

npm install -g jest-cli
npm install react-tools --save-dev

You will then need to configure the tool to suit your setup, the easiest way to do that being to amend the package.json file directly :

"jest": {
"rootDir": "relative/path/to",
"scriptPreprocessor": "<rootDir>/preprocessor.js",
"testDirectoryName": "tests",
"unmockedModulePathPatterns": ["<rootDir>/../../../../node_modules/react"]

Your test files will, according to this example, have to be located in a relative/path/to/tests folder. At the same level as this folder, you will have to set up a preprocessor.js file such as the following :

(function () {
'use strict';

var ReactTools = require('react-tools');

module.exports = {
process: function(src) {
return ReactTools.transform(src);

As you can see, we make use of the react-tools package we installed beforehand, which is meant to compile your JSX files in a standalone way in order to feed them to Jest (and, underneath, Jasmine).

The last line of the framework's configuration tells it not to mock React itself, as it automatically mocks pretty much everything and lets you decide what you want to preserve by using jest.dontMock('something') in your tests.

As for it, my personal recommandation would be to turn automocking off in the first place, as it has brought me more trouble than benefits. You can do that by using jest.autoMockOff(), and use the reverse logic to mock just what you need with jest.mock('something'). Actually, I have not been using that a lot, preferring to mock single methods here and there by replacing them with someModule.someMethod = jest.genMockFunction().

Speaking of mocks, you should know there currently is an open issue about the fact you cannot spy on stubbed method calls when these calls are meant to happen in response to an user event, such as onClick and the likes.

One great thing about tests is the way they make you think twice about your code. When using Jest, you will soon realize you want to avoid putting logic directly in methods such as componentWillMount, since they cannot be stubbed before the component's mounting into the DOM. Instead, put this logic in a separate function that will be called both by componentWillMount and manually in your test, so you can stub things and toy around with your component's data before updating its rendering.

If you need to mock a method that returns a promise and want to avoid using a dedicated library for that, here is a quick'n'dirty way to achieve just that :

then: function(callback) {

That will be all for now. Other small articles on the same topic may follow soon, stay tuned !

At the time of the writing of this article, I also had an issue where Jest would crash randomly, apparently because of some permission issue related to the .haste_cache folder. I tried running it with sudo, which not only worked but was not necessary anymore after the single time I used it.

Render a React component with attributes defined in the DOM

Using the JavaScript UI component library React is, among other benefits, a good way to disseminate small pieces of SPA intelligence into a more classical website, although it can sometimes be tricky to conciliate both worlds.

For this example, we will be building a form, one field of which holds a color value. We already set up a classic <input> to allow our users to type in the hexadecimal code they desire ; however, we would like to improve their experience by adding a colorpicker control that will change the field's value for them in a more pleasant way.

Having already been using React here and there throughout the project, we chose a library that makes use of it, and provides what we need as a React component. Since we want it to control the field, the latter needs to be rendered by React as well, which means we will roll out a component of our own that includes both.

We quickly face a dilemma, though : we still want the <input>'s value to be POSTed to the server under the right name, and we don't want to delegate to React the handling of CSS classes and such. All of the element's attributes shall keep being defined in our HTML template, for the sake of separation of concerns. Unfortunately, React doesn't allow us to fetch such data from the DOM when rendering its components out of the box : this is the issue we are going to address here.

First, let's define a target element for our component to render into (nothing new here) :

<div class="color-picker"></div>

We will now append every attribute we want applied to our <input> to this <div>, prepending the keys with data- to keep everything safe and valid :

<div class="color-picker" data-class="some-class" data-name="color" data-value="#BADA55"></div>

Now, we want the <input> rendered by React to get all these attributes applied to it (without the data- prefix, obviously), so everything not related to React keeps working just like without it. Here is our component's code :

var React = require('react'),
ReactColorPicker = require('react-color-picker');

module.exports = React.createClass({
getInitialState: function() {
return {
color: '#FFFFFF',
attrs: {}

updateColor: function(color) {
this.setState({ color: color.toUpperCase() });

// Called by React right after mounting the component in the DOM
componentDidMount: function() {
var parentNode = this.getDOMNode().parentNode,
attrs = this.state.attrs;

// We iterate over the target node (our div)'s attributes
[].slice.call(parentNode.attributes).forEach(function (attr) {
if (attr.name.match(/^data-/)) {
var realName = attr.name.substr(5);

if ('value' == realName) {
// The value will be handled by React directly, as a separate state variable
} else {
// This follows React's convention, class being a JS keyword
if ('class' == realName) {
realName = 'className';

// Other attributes will be grouped in an object
attrs[realName] = attr.value;

// Clean up the target node
}, this);

// We trigger our component's update to make it rerender with its new attributes
this.setState({ attrs: attrs });

render: function() {
// The {...var} notation allows us to apply a key-value JS object
// as a collection of HTML attributes
return (
<ReactColorPicker value={this.state.color} onDrag={this.updateColor} />
<input value={this.state.color} {...this.state.attrs} onChange={this.updateColor} />

Hopefully, future versions of the tool may allow us to render components dynamically based on the DOM's initial state more easily. A cleaner solution could have been to handle our field with a subcomponent and make these attributes part of its props, to enhance its reusability ; it would also be nice to display the <input> natively inside the <div>, so it remains available without JavaScript, but this might lead to some markup duplication - as for the attributes themselves, it should not be a problem if your form is part of a server-side template.

I will be glad to hear what you have to say about this, if you ever encountered similar situations and if you have a better solution to handle such cases : don't be shy !

Beware, mortals, for here be Patchwork

I'm thrilled to introduce Patchwork, a aimed at building websites I have been working on (and off) for the past two years, and that I just released in its 1.0.0 version.

Based on Silex, it integrates RedBean for model handling and has got some nifty things on the frontend side too, using Gulp for asset management.

It is available via Composer and can be installed and started through the command line like this :

composer create-project neemzy/patchwork pizza
cd pizza

Find out more and contribute at GitHub, and spread the word !

Incidentally, Patchwork uses my .

Use RedBean ORM with Silex micro-framework

As a PHP developer, I love using RedBean as an ORM and Silex as a micro-framework. But I have to admit the fact the former comes as a static class isn't quite handy sometimes.

I was looking for a solution to make the two of these communicate with each other in a better way. Some effort has already been put into it, but the linked package doesn't help with the main issue I described above, so I decided to roll out my own.

Here comes a RedBean service provider for Silex, available and following the PSR-2 and PSR-4 standards. It's dead simple, and mainly serves one purpose : make RedBean available as an instance through Silex's service containing capabilities (which should help with mocking while writing unit tests). Using it thus allows you to write code like the following :

$book = $app['redbean']->dispense('book');
$book->title = 'PHP for dummies';

As usual, I strongly encourage interested people to contribute to the project via GitHub !

As a side note, if you ever wanted to use my Environ along with Silex, I wrote a as well.