javascript - Promise not being resolved when run inside Jasmine unit tests -
facing strange issue when testing method returns promise in jasmine unit tests. have following class:
import http = require('http'); import https = require('https'); import fs = require('fs'); export default class imagedownloader { constructor(protected downloadpath:string) {} async download(url: string): promise<string> { return new promise<string>((resolve, reject) => { let file = fs.createwritestream(this.downloadpath, { autoclose: true }); let schema:any = url.startswith('https') ? https : http; schema.get(url, (response:fs.readstream) => { response.pipe(file).on('finish', () => resolve(this.downloadpath)); }).on('error', (error) => reject(error)); }); } }
it downloads image download path given in constructor, , resolves promise download path once file has been written disk.
i've written jasmine unit test:
import fs = require('fs'); import http = require('http'); import imagedownloader '../../src/image/imagedownloader'; describe('image downloader', () => { describe('download()', () => { it('returns path downloaded image', done => { spyon(http, 'get').and.callfake((url, cb) => { cb(fs.createreadstream(__dirname+'/../assets/elephpant.png')); }); let imagedownloader = new imagedownloader('/tmp/image'); imagedownloader.download('http://foo.bar/bazz.jpg').then((path) => { expect(path).toequal('/tmp/image'); done(); }); }); }); });
in test, mock node http
module in order return own faked "http response". remember node's incomingmessage
class (what returned response http.get()
) implements readable stream interface, i'm returning own readable stream fs.createreadstream()
.
when running test, times out because promise never getting resolved:
f failures: 1) image downloader download() returns path downloaded image 1.1) error: timeout - async callback not invoked within timeout specified jasmine.default_timeout_interval.
however, weird part if change part of download()
method resolves promise this:
response.pipe(file).on('finish', () => console.log('the promise resolved here'));
i see output:
the promise resolved here f failures: 1) image downloader download() returns path downloaded image 1.1) error: timeout - async callback not invoked within timeout specified jasmine.default_timeout_interval.
so we're getting part when promise called. it's i'm calling resolve()
promise not resolving reason.
Comments
Post a Comment