您好,感谢您抽出宝贵的时间阅读本文!
我非常有兴趣在开发过程中进行单元测试。我是Javascript测试的新手。
我编写了一个函数来读取我们选择的文件,带有输入,但是我不知道如何测试它。
我已经阅读了Jasmine的文档,关于间谍: https://jasmine.github.io/api/2.6/global.html#spyOn
和: https://jasmine.github.io/2.0/introduction.html
代码:
function readImage() {
if ( this.files && this.files[0] ) {
var FR= new FileReader();
var img = new Image();
FR.onload = function(e) {
img.src = e.target.result;
img.onload = function() {
ctx.drawImage(img, 0, 0, 512, 512);
};
};
FR.readAsDataURL( this.files[0] );
}
return [this.files, FR, img, ctx];
}
fileUpload.onchange = readImage;
我试过的测试:
describe('readImage', function () {
it('should get at least one file ', function () {
spyOn(window, 'readImage');
fileUpload.dispatchEvent(new Event('onchange'));
expect(window.readImage).toHaveBeenCalled();
})
});
此外,fileUpload是:
function createUploadInput() {
body = document.getElementsByTagName("BODY")[0];
upload = document.createElement("input");
upload.setAttribute("type", "file");
upload.setAttribute("id", "fileUpload");
body.appendChild(upload);
return upload;
}
createUploadInput();
我得到的输出:
Expected spy readImage to have been called.
Error: Expected spy readImage to have been called.
at jasmine.Spec.<anonymous> (test/readImageSpec.js:42:34)
我认为这是因为在测试中没有调用readImage方法。原因可能是因为fileUpload.dispatchEvent(new Event('onchange'));
什么都不做
你能帮我吗?
我也读过: How to trigger event in JavaScript?
Triggering event for unit testing
Using Jasmine to spy on a function without an object
感谢您的帮助!
我试过了:
it('should get at least one file ', function () {
spyOn(window, 'readImage');
fileUpload.dispatchEvent(new Event('change'));
expect(window.readImage).toHaveBeenCalled();
})
但输出是:
Expected spy readImage to have been called.
Error: Expected spy readImage to have been called.
at jasmine.Spec.<anonymous> (test/readImageSpec.js:42:34)
我也试过了:
it('should get at least one file ', function () {
spyOn(window, 'readImage');
fileUpload.onchange();
expect(window.readImage).toHaveBeenCalled();
})
输出:
Expected spy readImage to have been called.
Error: Expected spy readImage to have been called.
at jasmine.Spec.<anonymous> (test/readImageSpec.js:42:34)