Promise chains MT

17 views
Skip to first unread message

Tomasz Frydrych

unread,
Dec 8, 2015, 11:02:13 AM12/8/15
to bluebird
Hello,

I'm working on module test framework for big project, which use bluebird promises. There is some "event emiters/sources" - let's say in short they are our interfaces for external world. Most of them return Promise. I can easly mock them, so I can deliver my own implementation of Promise construction and save resolve/reject functions outside(to have possibility trigger them from test scope).

for example I can stub it this way:

original example emiter:
var XYZ = function()
{
this.register = function(filter)
{
return new Promise(function(resolve, reject)
{
if(filter >= 0 && filter < 10)
{
setTimeout(function(){ resolve({messageId: filter, data: "some data"}); }, Math.random() * 100); // as example
}
else
{
reject("unknown messageId");
}
});
};
};

mocked emiter:

var MockXYZ = function()
{
somehow.mock(this, "register");

this.triggers = {};

this.expectRegister= function(arg, trigger)
{
var self = this;
this.expect_call_register(function(filter)
{
somehow.expect_eq(arg, filter);
return new Promise(function(resolver, rejecter)
{
self.triggers[trigger] = {resolve: resolver, reject: rejecter};
});

});
};


this.resolve = function(trigger, v)
{

this.self.triggers[trigger].resolve(v);
};

this.reject = function(trigger, v)
{

this.triggers[trigger].reject(v);
};
};

so, in test I can write something like;

xyz = require("mockedXyz");

// then
xyz.expectRegister(1, "p1");
//when
someCodeToTest();

// then
wyz.expectRegister(2, "p1");
// when
xyz.resolve("p1", {messageId: 2, data: {}})

...

I know that there Bluebird after invoking resolve/reject will comeback to test scope before then(...) will be really executed but(I think) there is easy fix to make it synchronous for test purposes -> make bluebird sheduler implementation sync, so not use setImmedite(f) etc., just f();
-> shedule.js: module.exports = function(fn){ fn(); }

After that everything works fine, except that invoked reject (even if exist catch in "then" chain) produce warning about unhandled reject -> in real it's handled bacause of side effects visibility(for example prints). Anyone have Idea why in case of reject produce wired debug logs?

There is other possibility to not come back to "test context" from reject/resolve handler before then/catch will be executed?

This is needed only for test purposes to create strict scenarios where events are driven by test not background event loop.
Reply all
Reply to author
Forward
0 new messages