• Stars
    star
    103
  • Rank 333,046 (Top 7 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created about 10 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

DEPRECATED - Testing extensions for Mocha and Sinon

Build Status Project Status

DEPRECATED

Box has migrated to using Jest and no longer uses mocha or leche. We no longer support changes, pull requests, or upgrades to this package.

Leche

A JavaScript testing utility designed to work with Mocha and Sinon. This is intended for use both by Node.js and in browsers, so any changes must work in both locations.

Installation

There are slightly different installation instructions based on where you want to use Leche.

Including in Node.js

To include Leche in your Node.js project, go to your project directory and type:

npm i leche --save-dev

This command will automatically add Leche as a dependency inside of your package.json file. To include Leche in a Node.js file, use require():

var leche = require('leche');

The leche object is a singleton, so there is no need to initialize it.

Including in a Web Page

To include Leche in a web page, you can use RawGit.

The last published release:

<script src="https://cdn.rawgit.com/box/leche/master/dist/leche.js"></script>

Minified:

<script src="https://cdn.rawgit.com/box/leche/master/dist/leche.min.js"></script>

A specific version (in this example v2.1.0):

<script src="https://cdn.rawgit.com/box/leche/v2.1.0/dist/leche.js"></script>

Minified:

<script src="https://cdn.rawgit.com/box/leche/v2.1.0/dist/leche.min.js"></script>

Note: We highly recommend using a specific version as the master branch may change without notice.

A global leche object is created and is the same as the Node.js version.

Creating Objects

Sometimes in testing you need to quickly create an object with specific methods that don't do anything in particular. The leche.create() method lets you specify an array of methods to create, and it returns an object with those methods stubbed out to do nothing. For example:

var myObject = leche.create(["doSomething", "doSomethingElse"]);

myObject.doSomething();      // does nothing, actually
myObject.doSomethingElse();  // ditto

assert.ok(myObject.hasOwnProperty("doSomething"));       // passes
assert.ok(myObject.hasOwnProperty("doSomethingElse"));   // passes

Creating objects in this manner is useful when you don't have an original object from which to create a fake. You can pass this object into leche.fake() in order to create a fake (see next section).

Creating Fakes

Fakes are objects that share a prototype chain and method definitions of another object, but do not implement any of the methods. Instead, the methods throw exceptions when called. This makes fakes useful for testing in several ways:

  • You can create an object with the same interface as an actual object.
  • You can use this object with sinon.mock() to set expectations that override the default method behavior of throwing an error. This ensures that only methods with expectations explicitly set can be called.
  • The fake will pass any instanceof checks that the original object would pass.

Additionally, fakes contain all of the properties of the passed-in object. In ECMAScript 5 environments, accessing these properties without first setting them to a value will result in an error.

To create a fake, pass in the object you want to fake to leche.fake(), such as:

// source
function Person(name) {
    this.name = name;
}

Person.prototype.sayName = function() {
    console.log(this.name);
};

Person.prototype.sayHi = function() {
    console.log('Hi!');

};

// in a test
var fakePerson = leche.fake(new Person('Jeff'));

assert.ok(fakePerson instanceof Person);  // passes
assert.ok('sayName' in fakePerson);       // passes
assert.ok('name' in fakePerson);          // passes

// throws an error
fakePerson.sayName();

// also throws an error
var name = fakePerson.name;

// won't throw an error because you've assigned a value
fakePerson.name = 'Jeff';
var name = fakePerson.name;

Fakes are useful for creating mocks, where you set an expectation that a certain method will be called. Sinon will redefine the method with the expectation and no error will be thrown. However, trying to call any other method on the fake will result in an error. For example:

 // in a test
var fakePersonMock = leche.fake(Person.prototype);
var fakePersonMockHandler = sinon.mock(fakePersonMock);

fakePersonMockHandler.expects('sayName');

fakePersonMock.sayName();    // no error - Sinon has mocked it out
fakePersonMock.sayHi();      // throws an error

This pattern is useful for a couple reasons:

  1. Sinon will not let you set an expectation for a method that doesn't exist on fakePerson. It will throw an error.
  2. Leche won't let you call a method for which an expectation has not been set. It will throw an error.

These features let you test the interface of existing objects in a robust and less error-prone way.

Mocha Data Provider

Leche has a Mocha-specific data provider implementation called withData(). The intent of withData() is to mimic the QUnit.cases functionality in QUnit, allowing you to run the same tests over multiple values in a dataset. The basic format (using labels) is:

var withData = leche.withData;

describe('MyObject', function() {

    withData({
        label1: [1, 2],
        label2: [3, 4]
    }, function(first, second) {

        it('should say the values are equal when they are passed', function() {
            assert.equal(first, second);
        });
    });
});

In this example, there are two data sets. The first is called "label1" and has an array of two values. The second is called "label2" and also has an array of two values. The label is used as part of the output from Mocha when an error occurs in the test. The arrays are used to specify the arguments that should be passed into the function. In this example, first would be 1 for the first dataset and second would be 2. For the second dataset, first would be 3 and second would be 4.

Naming tests when using withData with labels

When using the label form of withData(), you should name the labels so that they complete the sentence created by your "it('should...')" definition. For example:

describe('getSharedLinkForPadByClientID', function() {
    withData({
        'no fileId in session': [{authToken: 'abcdef123456'}],
        'no authToken in session': [{fileId: '123456678'}],
    }, function(sessionInfo) {
        it('should send error to client', function() {
            //...
        });
    });
});

If both these test failed, the outputted error message would look like:

1) getSharedLinkForPadByClientID with no fileId in session should send error to client
2) getSharedLinkForPadByClientID with no authToken in session should send error to client

withData() without labels

You can also pass data without labels, and withData() will do its best to create a label that makes sense:

var withData = leche.withData;

describe('MyObject', function() {

    withData([
        [1, 2],
        [3, 4]
    ], function(first, second) {

        it('should say the values are equal when they are passed', function() {
            assert.equal(first, second);
        });
    });
});

This is the same as the previous example, except the labels will come out as "1,2" for the first dataset and "3,4" for the second.

Frequently Asked Questions

What is "Leche"?

You put leche in your mocha to make it taste awesome.

Build System

This project uses make for its build system, but you should use npm for executing commands. The following commands are available:

  • npm test - runs linting and unit tests (plus code coverage)
  • npm run lint - runs just linting
  • npm run jsdoc - creates JSDoc documentation

Developing Leche

  1. Clone this repo.
  2. Run npm install.
  3. Run npm test to ensure everything is working.
  4. Profit.

Support

Need to contact us directly? Email [email protected] and be sure to include the name of this project in the subject.

Copyright and License

Copyright 2014-2015 Box, Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

More Repositories

1

spout

Read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way
PHP
4,219
star
2

t3js

DEPRECATED - A minimal component-based JavaScript framework
JavaScript
1,557
star
3

Anemometer

Box SQL Slow Query Monitor
JavaScript
1,369
star
4

kube-applier

kube-applier enables automated deployment and declarative configuration for your Kubernetes cluster.
Go
630
star
5

kube-iptables-tailer

A service for better network visibility for your Kubernetes clusters.
Go
538
star
6

box-ui-elements

React Components for Box's Design System and Pluggable Components
JavaScript
532
star
7

box-python-sdk

Box SDK for Python
Python
420
star
8

mojito

An automation platform that enables continuous localization.
Java
367
star
9

flaky

Plugin for nose or pytest that automatically reruns flaky tests.
Python
347
star
10

viewer.js

A viewer for documents converted with the Box View API
JavaScript
335
star
11

stalker

A jQuery plugin allowing elements to follow the user as they scroll a page.
JavaScript
227
star
12

boxcli

A command line interface for interacting with the Box API.
JavaScript
197
star
13

box-windows-sdk-v2

Windows SDK for v2 of the Box API. The SDK is built upon .NET Framework 4.5
C#
186
star
14

ClusterRunner

ClusterRunner makes it easy to parallelize test suites across your infrastructure in the fastest and most efficient way possible.
Python
180
star
15

box-node-sdk

A Javascript interface for interacting with the Box API. You can find the node package at
JavaScript
177
star
16

augmented_types

A PHP extension to enforce parameter and return type annotations
C++
166
star
17

bart

A collection of our critical PHP tools
PHP
163
star
18

box-java-sdk

The Box SDK for Java.
Java
156
star
19

memsniff

A tool for recording and displaying statistics on memcached traffic written in golang.
Go
143
star
20

genty

Genty, pronounced "gen-tee", stands for "generate tests". It promotes generative testing, where a single test can execute over a variety of input.
Python
119
star
21

box-ios-sdk

iOS SDK for the Box Content API
Swift
117
star
22

kube-exec-controller

An admission controller service and kubectl plugin to handle container drift in K8s clusters
Go
109
star
23

RainGauge

RainGauge
JavaScript
107
star
24

box-content-preview

JavaScript library for rendering files stored on Box
JavaScript
105
star
25

box-openapi

OpenAPI 3.0 Specification for the Box APIs
JavaScript
93
star
26

rotunicode

Python library for converting between a string of ASCII and Unicode chars maintaining readability
Python
77
star
27

brainy

A faster, safer templating library for PHP
PHP
66
star
28

mysqlutilities

Box's MySQL Utilities
Shell
65
star
29

samples

Code snippets and samples to demonstrate how to get the most out of the Box platform & API
JavaScript
64
star
30

box-android-sdk

Java
62
star
31

box-salesforce-sdk

This is the Salesforce SDK for integrating with the Box Platform.
Apex
57
star
32

box-android-apptoapp-sdk

This SDK supports Box OneCloud integrations on Android that handle file โ€˜roundtripsโ€™. That is, it enables file open-edit-save scenarios between the Box app and partner apps without the need for partner apps to authenticate a Box user independently.
Java
57
star
33

fast_assert

PHP
37
star
34

StatusWolf

Configurable operations dashboard designed to bring together the disparate datasources that operations teams need to manage and present them in a flexible and beautiful way.
PHP
36
star
35

shmock

SHorthand for MOCKing in PHPUnit
PHP
34
star
36

Makefile.test

A makefile used for running test executables
Python
32
star
37

error-reporting-with-kubernetes-events

A demonstration of how Box utilizes Kubernetes CustomResourceDefinitions and Events
Go
32
star
38

box-skills-kit-nodejs

Official toolkit library and boilerplate code for developing Box Skills.
JavaScript
27
star
39

box-python-sdk-gen

Repository for generated Box Python SDK
Python
26
star
40

shalam

DEPRECATED - A friendly tool for CSS spriting
JavaScript
25
star
41

developer.box.com

Box Developer Documentation - Content & Configuration
JavaScript
24
star
42

box-ios-browse-sdk

Objective-C
18
star
43

wavectl

Command Line Client For Wavefront
Python
18
star
44

box-ios-preview-sdk

Box iOS Preview SDK
Swift
17
star
45

clusterrunner-javascript-sdk

ClusterRunner JavaScript SDK that works in both node and browsers
HTML
16
star
46

box-typescript-sdk-gen

Repository for generated Box TS SDK
TypeScript
15
star
47

box-ui-elements-demo

Demo react app for UI Elements
JavaScript
14
star
48

sdks

SDKs, CLI and other tools for using Box Platform
14
star
49

box-android-preview-sdk

Box Android Preview SDK
Java
13
star
50

box-android-browse-sdk

Java
12
star
51

hdrCompressor

Tool for saving HDR file as RGBM, RGBD, RGBE or LogLuv TGA file.
C
12
star
52

box-annotations

JavaScript library for annotations on files rendered with Box Content Preview
TypeScript
11
star
53

etcdb

Etcd PEP 249 driver.
Python
10
star
54

box-content-preview-demo

Demo React App using the Preview UI Element
JavaScript
8
star
55

box-postman

The official Box Postman Collection
JavaScript
7
star
56

box-dotnet-sdk-gen

Repository for Box .NET autogenerated SDK
C#
6
star
57

verold.github.io

Verold developer docs and tutorials
JavaScript
5
star
58

uploaders

Write your own custom uploader to send 3D models/textures to Verold Studio.
4
star
59

box-ios-share-sdk

Objective-C
4
star
60

box-windows-metadata-sdk-v2

Box Metadata C# SDK Plugin
C#
4
star
61

homebrew-mojito

Homebrew tap for Box/mojito
Ruby
3
star
62

box-developer-changelog

Box Developer Changelog
JavaScript
3
star
63

box-languages

Languages used by other box projects
JavaScript
2
star
64

box-android-share-sdk

Java
2
star
65

puppet-clusterrunner

Installs ClusterRunner using Puppet
Puppet
2
star
66

box-java-sdk-samples

Sample apps for the Box Java SDK.
Java
2
star
67

cla

Landing page for CLA Agreements
1
star