最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to mock dom element from karma testing - Stack Overflow

programmeradmin0浏览0评论

There is an input type file element. During angular file upload multiple times, the value is not being cleared. Hence manually clearing it using plain javascript dom manipulation.

Below is the code:

function removeFromQueue(item) {
        vm.uploads.uploader.removeFromQueue(item);
        // Clearing input file field for re-uploading
        if(!vm.uploadFile) {
            document.getElementById('upload-file-' + vm.type).value = null;
        }
    }

In this case, not able to mock the document.getElementById, hence controlling it using vm.uploadFile undefined variable from unit test case which is wrong. How to mock the dom element here?

There is an input type file element. During angular file upload multiple times, the value is not being cleared. Hence manually clearing it using plain javascript dom manipulation.

Below is the code:

function removeFromQueue(item) {
        vm.uploads.uploader.removeFromQueue(item);
        // Clearing input file field for re-uploading
        if(!vm.uploadFile) {
            document.getElementById('upload-file-' + vm.type).value = null;
        }
    }

In this case, not able to mock the document.getElementById, hence controlling it using vm.uploadFile undefined variable from unit test case which is wrong. How to mock the dom element here?

Share Improve this question asked May 15, 2017 at 7:19 Mithun ShreevatsaMithun Shreevatsa 3,60910 gold badges58 silver badges104 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 17

You should be able to spyOn the document.getElementById and return the useful properties (i.e. value here). Like this,

spyOn(document, "getElementById").and.callFake(function() {
    return {
        value: 'test'
    }
}); 

And then if you want, you can expect it to have been called,

expect(document.getElementById).toHaveBeenCalledWith('...')
发布评论

评论列表(0)

  1. 暂无评论