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

fn-tester

v1.0.2

Published

A tiny utility to record function calls and define test doubles.

Downloads

9

Readme

fn-tester is a tiny utility to record function calls and define test doubles for JavaScript/Node.js. It has no dependencies and can be used with virtually all testing frameworks.

Installation

Node.js

npm install --save-dev fn-tester

Browsers

Install as above and use the fn-tester.js file found in the node_modules directory:

<script src="./node_modules/fn-tester/fn-tester.js"></script>

Usage

fn-tester is a simple as it gets. It has only three options and one method to use. fn-tester requires running functions indirectly by using a variation of the Command design pattern, which is necessary to intercept all function calls and preserve the value of "this".

var fn = require('fn-tester');

// Instead of parentObj.methodName(argument1, argument2, ...), use:
fn.run(parentObj, 'methodName', argument1, argument2, ...);

// For simple functions, use:
fn.run(myFunction, null, argument1, argument2, ...);

It may be argued that changing all function calls isn’t simple at all, but there is no need to change every single function call. In a typical Model-View-Controller (MVC) application, modifying controller-level functions that deal with running multiple services should mostly be sufficient. Services that deal with databases and remote APIs need to have test doubles in any case.

fn-tester can be configured by simply changing the test property, and the defaults are:

fn.test = { enabled: false, calls: [], doubles: [] };

When enabled is true, fn-tester starts to record function calls in calls. It also runs the test double functions stored in doubles (if any) instead of the originals.

Here is how to define test doubles for a simple user account creation controller:

// (...)

var userService = {
    hashPassword: function (password) {
        return bcrypt.hash(password, 8);
    },

    getUserByEmail: function (email) {
        return db('user').where('email', email).then(_.head);
    },

    insertUser: function (email, name, password) {
        return db('user').insert({ email, name, password }).returning('id');
    },
};

function createUser(email, name, password) {
    return fn.run(userService, 'getUserByEmail', email).then((existingUser) => {
        if (existingUser) {
            return Promise.reject('error.duplicateEmail');
        }
        return fn
            .run(userService, 'hashPassword', password)
            .then((passwordHash) => fn.run(userService, 'insertUser', email, name, passwordHash));
    });
}

fn.test = {
    enabled: true,
    calls: [],
    doubles: [
        function getUserByEmail() {
            return Promise.resolve();
        },
        function hashPassword() {
            return Promise.resolve('hash');
        },
        function insertUser() {
            return Promise.resolve(1);
        },
    ],
};

fn.run(createUser, null, 'some@email', 'name', 'pass').then(() => console.log(fn.test.calls));

When fn-tester finds a function in test.doubles with the same name as the function called, runs the test double instead of the original. test.calls contains the function calls complete with the arguments passed.

[
    ['createUser', 'some@email', 'name', 'pass'],
    ['getUserByEmail', 'some@email'],
    ['hashPassword', 'pass'],
    ['insertUser', 'some@email', 'name', 'hash'],
];

test.calls is useful to determine if a function is called and has received the correct arguments.

Finally, here is an example how fn-tester can be used with Chai and Mocha:

var fn = require('fn-tester');
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
var should = chai.should();
chai.use(chaiAsPromised).should();

// (...)

describe('createUser', function () {
    it('should go through with account creation', async function () {
        fn.test = {
            enabled: true,
            calls: [],
            doubles: [
                function getUserByEmail() {
                    return Promise.resolve();
                },
                function hashPassword() {
                    return Promise.resolve('hash');
                },
                function insertUser() {
                    return Promise.resolve(1);
                },
            ],
        };
        await fn
            .run(createUser, null, 'some@email', 'name', 'pass')
            .then(() =>
                fn.test.calls.should.be
                    .an('array')
                    .that.deep.includes(['getUserByEmail', 'some@email'])
                    .and.that.deep.includes(['hashPassword', 'pass'])
                    .and.that.deep.includes(['insertUser', 'some@email', 'name', 'hash'])
            );
    });
});