mardi 23 mai 2017

Stubbing one method that calls a real method with jasmine

I need to test a FileReader's onload, using Jasmine + Sinon.

This is the function to be tested:

MyObject.prototype.uploadFile = function (file, callback) {
    const fileReader = new FileReader();

    fileReader.onload = event => {
        if (typeof callback === 'function') {
            callback(event);
        }
    };

    fileReader.readAsDataURL(file);
};

And this is the test:

describe('uploadFile', () => {
        it('should execute the callback', () => {
            let testFunction = jasmine.createSpy();
            let readData = {
                readAsDataURL: () => { 
                    this.onload();
                },
                onload: () => {
                }
            };

            file = new Blob(['image']);
            sandbox.stub(window, 'FileReader').returns(readData);

            component = sandbox.render(BioProfile);
            component.replaceImage(file, testFunction);

            expect(testFunction).toHaveBeenCalled();
        });
    });

As you can see, I stubbed readData from FileReader (not sure if done properly, though), but I need a stubbed method to call a FileReader's actual method (onload) to be able to test.

Is that possible?

Aucun commentaire:

Enregistrer un commentaire