testing - 用 jasmine stub 一个调用真实方法的方法

标签 testing jasmine filereader sinon

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

这是要测试的函数:

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 进行了 stub (尽管不确定是否正确完成),但我需要一个 stub 方法来调用 FileReader 的实际方法 (onload) 以便能够进行测试。

这可能吗?

最佳答案

你 stub 了 FileReader不正确。

使用对象文字,this是构造对象字面量的上下文。

除非您使用es6中介绍的速记符号.

所以当你调用this.onload里面readAsDataURL , 它没有尝试调用 onload readData 上的函数对象。

这样做:

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

关于testing - 用 jasmine stub 一个调用真实方法的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44146200/

相关文章:

java - 为什么FileReader没有flush,而FileWriter有呢?

java - Mockito:监视被测系统中依赖于 HTTP 请求的方法是不好的做法吗?

Angular 2测试: calling function directly cannot change the component object itself

javascript - Grunt 和 hood.ie 测试数据库

python - 处理大文件的最快方法?

javascript - JS脚本自动导入文件,无需输入按钮

reactjs - Jest 模拟模块解析变量值

testing - 如何将 Ivy 凭据传递给脚本测试?

testing - Visual Studio 负载测试不断发送请求

node.js - Node.js 上的 Geddy MVC 单元测试框架