promise-helper-for-deferred-style-resolve
v0.0.1
Published
Simple promise helper for calling resolve at outside of promise constructor like jQuery.deferred
Downloads
2
Readme
promise-helper-for-deferred-style-resolve
A promise helper for deferred style resolve.
You can write tests easily, without any jQuery.
How to use
Get promise objcet, resolve & reject functions via promiseDeferred()
var promiseDeferred = require('promise-helper-for-deferred-style-resolve');
var response = promiseDeferred(function() {
return successCallback(data);
}, function() {
return failCallback(data);
});
# response object is
# {
# promise: promise,
# resolve: resolve,
# reject: reject
# }
If you want writing success case, you just write response.resolve()
, in your test case, The success calback will be called. And, you can also do failed case, call response.reject()
.
You can assert (and resolve) like below code.
response.then(function() {
assert(callback.withArgs("success").calledOnce);
done()
});
response.resolve();
For example.
assert = require 'power-assert'
sinon = require 'sinon'
request = require 'superagent'
deferred = require 'promise-deferred'
ToDo = require './ToDo'
describe "load all", ->
beforeEach ->
sinon.stub(request, 'get', (url, cb) ->
ok = {ok: true, status: 200, text: "OK"}
ng = {ok: false, status: 404, text: "Not Found"}
return deferred(() -> cb ok, () -> cb ng)
)
afterEach ->
request.get.restore()
it "call the ajax once", () ->
ToDo.loadAll(sinon.spy()).resolve()
assert(request.get.calledOnce)
it "yield success", () ->
callback = sinon.spy()
{promise, resolve} = ToDo.loadAll(callback)
promise.then(()->
assert(callback.withArgs(200, [t]).calledOnce)
done()
).catch((e) -> done(e))
resolve()
it "yield error", () ->
callback = sinon.spy()
{promise, reject} = ToDo.loadAll(callback)
promise.then(()->
assert(callback.withArgs(400).calledOnce)
done()
).catch((e) -> done(e))
reject()