我需要使用 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/