Skip to content

Instantly share code, notes, and snippets.

View pmeskers's full-sized avatar

Paul Meskers pmeskers

View GitHub Profile

Testing JavaScript's native Promises

Promises are not a new concept to JavaScript, with popular implementations already provided by jQuery and Q. However, with the Promise abstraction now a built-in object in ECMAScript and appreciating more widespread browser support, it makes sense to start shifting towards this new interface.

Because of their asynchronous nature, promises can often be confusing to unit test. The purpose of this post will be to demonstrate a simple example of how one might apply TDD and build a test suite around a simple JavaScript service which returns a promise.

In the spirit of using new JS interfaces, we'll also be using the new Fetch API as our asynchronous behavior, and we'll be writing our unit tests in [Jasmine](http://jasmine.github.io/2.0/intro

ES6 Classes, Autobinding, and You

So you've started using ES6 classes and you notice something unexpected. In some contexts, certain methods on your classes are not able to reference their class members! Let's take a look at a possible example.

This breakdown assumes familiarity with new ES6 syntax, as well as a basic understanding of how this is assigned to function invocations.

The Problem

Example 1

Let's say we have an index filled with publisher documents. A publisher has a collection of books, and each book has a title, a published flag, and a collection of genre scores. A genre_score represents how well a particular book matches a particular genre, or in this case a genre_id.

First, let's define some mappings (for simplicity, we will only be explicit about the nested types):

curl -XPUT 'localhost:9200/book_index' -d '
  {
    "mappings": {