node-file-handler.ts 2.29 KB
import { NodeFileHandler } from '../../../src/file-handler/node-file-handler';
import * as http from 'http';
import * as https from 'https';
import * as fs from 'fs';

describe("Node Downloader", () => {

    let nodeFileHandler = new NodeFileHandler();

    it("should retrieve right handler", () => {

        let httpHandler = nodeFileHandler.selectProtocol("http://someurl.com/image.jpg");
        expect(httpHandler).toEqual(http);

        let httpsHandler = nodeFileHandler.selectProtocol("https://someurl.com/image.jpg");
        expect(httpsHandler).toEqual(https);

        let nullHandler = nodeFileHandler.selectProtocol("notsupported://blub");
        expect(nullHandler).toBeNull();

    });

    it("should download sample image from https source and store with new name", (done) => {

        let source = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/800px-FullMoon2010.jpg";
        let target = ".tmp/full-moon.jpg";
        let lastProgress = 0;

        nodeFileHandler.download(source, target)
            .subscribe(
                (progress: number) => {
                    expect(progress).toBeGreaterThan(lastProgress);
                    lastProgress = progress;
                } ,
                (error:any) => {} ,
                () => { 
                    expect(lastProgress).toEqual(1);
                    expect(fs.existsSync(target)).toBeTruthy();
                    done();
                }
            );
    });

    it('should not download if file with same name exists and bytesize > 0', (done) => {
        let source = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/800px-FullMoon2010.jpg";
        let target = ".tmp/full-moon-sensless.jpg";
        let lastProgress = 0;

        let file = fs.createWriteStream(target, {'flags': 'a'});
        let dummyData = "some sensless information to fill bytes...";
       
        file.write(new Buffer(dummyData));
        file.end(() => {

            nodeFileHandler.download(source, target)
            .subscribe(
                () => { fail("progress should not be called"); } ,
                () => {} ,
                () => {
                    expect(fs.existsSync(target)).toBeTruthy();
                    done();
                }
            );

        });
    });

});