How to mock dom element from karma testing
19,577
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('...')
Author by
Mithun Shreevatsa
Software Engineer practicing Frontend more these days and backend less. Familiar with technologies like Javascript, React, Angular, PHP, MySQL and Node.js
Updated on June 30, 2022Comments
-
Mithun Shreevatsa almost 2 years
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 usingvm.uploadFile
undefined variable from unit test case which is wrong. How to mock the dom element here? -
Neurothustra over 5 yearsin this example, how does the test know which id is being called? for example, the id: 'upload-file-upload-file-' + vm.type` isn't being passed anywhere in your example. edit: removed template literal to match OPs example
-
Ashutosh Singh almost 4 yearsafter upgrading to "@types/jasmine": "^3.4.0" the same code throws error