javascript - Mocha - Testing Promise, `done` never gets called in Promise -
i'm trying test spy called in .then block of promise, done in then block doesn't seem executed @ all.
i'm getting timeout of 2000ms exceeded.
here's i'm testing (async):
/** * passed down loginform component * handle form submission. */ _submithandler(data) { return function(evt) { evt.preventdefault && evt.preventdefault(); evt.stoppropagation && evt.stoppropagation(); return request('post', 'auth', data) .then((res) => { authactions.login(); return res; }) } } here's test:
describe('when succeeds', () => { it('should login', (done) => { sinon.spy(authactions, 'login'); instance._submithandler({})({}) .then((res) => { console.log('called!!!'); expect(authactions.login.called).to.equal(true); authactions.login.restore(); done(); }, done); }); }); i'm using karma run tests; chai , sinon.
i had issue, cause trying respond xhr before connection opened, e.g.
this code throw invalid_state_err - 0 fakexmlhttprequest.setresponseheaders:
describe("get", function () { beforeeach(function () { this.xhr = sinon.usefakexmlhttprequest(); this.xhr.oncreate = function (request) { request.respond(200, null, ""); }; }); aftereach(function () { this.xhr.restore(); }); it("should make request", function () { myobject.get("testurl"); }); }); this code works:
describe("get", function () { beforeeach(function () { this.xhr = sinon.usefakexmlhttprequest(); this.requests = []; this.xhr.oncreate = function (request) { this.requests.push(request); }; }); aftereach(function () { this.xhr.restore(); }); it("should make request", function () { myobject.get("testurl"); this.requests[0].respond(200, null, ""); }); }); reading documentation, show same technique of pushing requests array, had subconsciously , inaccurately came away impression oncreate, despite name, more "on request".
myobject.get = function (url) { var http = new xmlhttprequest(); // xhr instance exists // readystate 0 // oncreate runs http.open("get", url); http.send(); // readystate 1 // can call setresponseheaders , respond } the result have put respond code after call method runs xmlhttprequest's send, as:
myobject.get("testurl"); this.requests[0].respond(200, null, ""); i using respond method, same true setresponseheaders(respond calls setresponseheaders)--in test called early.