【问题标题】:Stubbing one method that calls a real method with jasmine用茉莉花调用一个真正的方法的方法
【发布时间】:2017-05-23 22:42:26
【问题描述】:

我需要使用 Jasmine + Sinon 测试 FileReader 的 onload。

这是要测试的功能:

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

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

    fileReader.readAsDataURL(file);
};

这是测试:

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();
        });
    });

如您所见,我从 FileReader 存根 readData(但不确定是否正确完成),但我需要一个存根方法来调用 FileReader 的实际方法(onload)才能进行测试。

这可能吗?

【问题讨论】:

    标签: testing jasmine filereader sinon


    【解决方案1】:

    你错误地存根FileReader

    对于对象字面量,this 是构造对象字面量的任何上下文。

    除非您使用es6 中引入的简写符号。

    因此,当您在 readAsDataURL 中调用 this.onload 时,它不会尝试在 readData 对象上调用 onload 函数。

    这样做:

    let readData = {
        readAsDataURL() { 
            this.onload();
        },
        onload() {}
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 2016-09-24
      • 2016-07-13
      • 1970-01-01
      相关资源
      最近更新 更多