Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock dom element from karma testing

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?

like image 706
Mithun Shreevatsa Avatar asked May 15 '17 07:05

Mithun Shreevatsa


1 Answers

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('...')
like image 197
tanmay Avatar answered Sep 17 '22 17:09

tanmay