samedi 28 novembre 2015

Mocking Node.js module in Sinon still calls actual module

I'm starting to write tests for a node.js server I'm writing. I'm trying to test this function

exports.get_device_states = function (body, master_callback) {
    var state = new State(body[State.id_key]);
    console.log("STATE: ");
    console.log(state);

    mysqlDao.get_device_states_for_group(state, function(err, result) {
        var resp_json = {
            'error': err,
            'stateList': result
        }

        master_callback(resp_json);
    });
}

I need to mock the 'mysqlDao' module that I use to read/write to my db. but I was unable to do this. Whenever I try. I still get the actual db results back.

messagesTest.js

var sandbox = sinon.sandbox.create();
var stubbedDao = {
    get_device_states_for_group: sandbox.stub().returns("STUBBED")
}

...

describe('messages', function() {

    before(function() {
        mockery.enable();
    });

    beforeEach(function() {
        mockery.registerAllowable('async');
        mockery.registerAllowable('../models/State');
        mockery.registerAllowable('../models/Message');
        mockery.registerMock('../dao/gcmdao', stubbedDao);

        messages = require('../business/messages.js');
    });

    afterEach(function() {
        sandbox.verifyAndRestore();
       mockery.deregisterAll(); 
    });

    after(function() {
        mockery.disable();
    });


    describe('get_device_state', function () {
        it('isNormal', function () {
            var body = {
                "STATE_ID": testData.state_one
            }

            stubbedDao.get_device_states_for_group.yields();

            messages.get_device_states(body, function(resp) {
                console.log("returns");
                assert(stubbedDao.get_device_states_for_group.calledOnce);
                console.log(resp);
            })

        });
    });
});

But instead of returning "STUBBED" Like I want it to. It just returns the Db results. It's not a huge issue for read functions but I need this to work so that I don't modify the db on other tests.

Thanks, A.L

Aucun commentaire:

Enregistrer un commentaire