用 jasmine 存根一个调用真实方法的方法
Stubbing one method that calls a real method with jasmine
我需要使用 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(尽管不确定是否正确完成),但我需要一个存根方法来调用 FileReader 的实际方法 (onload) 才能进行测试。
这可能吗?
你打错了FileReader
。
对于对象字面量,this
是构造对象字面量的上下文。
除非您使用es6
中介绍的shorthand符号。
因此,当您在 readAsDataURL
中调用 this.onload
时,它不会尝试在 readData
对象上调用 onload
函数。
为此:
let readData = {
readAsDataURL() {
this.onload();
},
onload() {}
};
我需要使用 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(尽管不确定是否正确完成),但我需要一个存根方法来调用 FileReader 的实际方法 (onload) 才能进行测试。
这可能吗?
你打错了FileReader
。
对于对象字面量,this
是构造对象字面量的上下文。
除非您使用es6
中介绍的shorthand符号。
因此,当您在 readAsDataURL
中调用 this.onload
时,它不会尝试在 readData
对象上调用 onload
函数。
为此:
let readData = {
readAsDataURL() {
this.onload();
},
onload() {}
};