Giter Club home page Giter Club logo

pubnub-functions-mock's Introduction

PubNub Functions Mock

Build Status Coverage Status Known Vulnerabilities

Unit test PubNub Functions event handlers on your local machine

Currently supported modules for mock (docs here):

Any module can be overridden using overrideDefaultModules within a single test body. The module or modules will only be overridden in that single test block.

endpoint.overrideDefaultModules({
    "xhr" : () => {
        return Promise.resolve(200);
    }
});

To override a default module in all tests, pass the module object when the Event Handler is initialized.

endpoint = Mock('./myEndpointEventHandler.js', { 
    "xhr" : () => {
        return Promise.resolve(200);
    }
});

Mock the KVStore for a test

endpoint.mockKVStoreData({"key":"value"});

Mock the KVStore counters for a test

endpoint.mockKVStoreCounters({"key":123});

Example PubNub Function Endpoint unit test with Mocha and Chai

// myTest.js
const assert = require('chai').assert;
const Mock = require('pubnub-functions-mock');

const endpointRequestObject = {
    "body": "{}",
    "message": {},
    "method": null,
    "params": {}
};

const endpointResponseObject = {
    "headers": {},
    "status": 200,
    "send": function ( body ) {
        return new Promise( (resolve, reject) => {
            resolve({
                "body": body || "",
                "status": this.status
            });
        });
    }
};

describe('#endpoint', () => {
    let endpoint;

    beforeEach(() => {
        endpoint = Mock('./myEndpointEventHandler.js');
    });

    it('creates endpoint event handler of type Function', (done) => {
        assert.isFunction(endpoint, 'was successfully created');
        done();
    });

    it('returns "Hello World!"', (done) => {
        
        let request = Object.assign({}, endpointRequestObject);
        let response = Object.assign({}, endpointResponseObject);

        let correctResult = {
            "body": "Hello World!",
            "status": 200 
        };

        endpoint(request, response).then((testResult) => {

            assert.equal(testResult.status, correctResult.status, 'status');
            assert.equal(testResult.body, correctResult.body, 'response body');

            done();
        });
    });

    it('returns a kvstore value', (done) => {
        
        let request = Object.assign({}, endpointRequestObject);
        let response = Object.assign({}, endpointResponseObject);

        request.getKvValue = true;

        let preExistingValue = { "key" : "value" };

        let correctResult = {
            "body": preExistingValue.key,
            "status": 200 
        };

        // Mock the pre-existing KVStore value for this test only
        endpoint.mockKVStoreData(preExistingValue);

        endpoint(request, response).then((testResult) => {

            assert.equal(testResult.status, correctResult.status, 'status');
            assert.equal(testResult.body, correctResult.body, 'response body');

            done();
        });
    });
});

The above test would be run on myEndpointEventHandler.js using mocha myTest

// myEndpointEventHandler.js
export default (request, response) => {
    const pubnub = require('pubnub');
    const kvstore = require('kvstore');

    if (request.getKvValue) {
        return kvstore.get('key').then((value) => {
            response.status = 200;
            return response.send(value);
        });
    }

    response.status = 200;
    return response.send("Hello World!");
};

pubnub-functions-mock's People

Contributors

ajb413 avatar crgbaumgart avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

pubnub-functions-mock's Issues

overrideDefaultModules does not work of there is more than one export

If you create a pubnub script with several exports, the overrideDefaultModules stops working.

Example pubnub script:

//before publish handler
export default (request) => { 
    const db = require('kvstore');
    sendToSlack('some message')
}

const xhr = require('xhr');

export function sendToSlack(message)
{

    let http_options = {
        "method": "POST",
        "headers": {
            "Content-Type": "application/json"
        },
        "body": JSON.stringify({
            "text": message,
            "username": "Some Bot"
        })
    };

    let url = "https://hooks.slack.com/services/SOME_URL";

    return xhr.fetch(url, http_options).then((x) => {
        const body = JSON.parse(x.body);
        console.log(body);
        return request.ok();
    });
}

In this case, mocking XHR does nothing, the HTTP are executed for real :(

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.