Creating HTML elements for javascript testing

泄露秘密 提交于 2019-12-02 09:45:59

问题


So i have a particular problem, inside my react component i used commands like these:

document.getElementById('modalsContainer').appendChild(recognitionProfileZoom);
document.getElementById('modalsContainer').appendChild(categoryZoom);

and:

document.getElementById('cddoccategoryzoom').value;

But these elements that were specified by ID don't exist in my component.
How would one go about creating these objects on the tests?

The code below would use these elements but it fails because they don't exist(the hideModal function utilizes the document.append from before)

describe("CaptureProfileModal functions tests", function() {

it('Should hide the modal', function() {
    var wrapper, instance;

    wrapper = mount(
        <CaptureProfileModal
            gridAction={1}
            captureSettingCode={15}
            fields={mockedFields}/>
    );

    wrapper.setState({
        showModal: true
    });

    instance = wrapper.component.getInstance();
    instance.hideModal();
});

回答1:


Creating DOM elements in your enzyme tests:

So guys, to create DOM elements in your test, it's actually really simple and you type it just as you would in vanilla javascript, with the global keyword:

it('Should hide the modal', function() {
        var wrapper, instance;
        var modalsContainer = global.document.createElement('div');
        var recognitionProfileZoom = global.document.createElement('div');
        var categoryZoom = global.document.createElement('div');

        modalsContainer.id = 'modalsContainer';
        recognitionProfileZoom.id = 'recognitionProfileZoom';
        categoryZoom.id = 'categoryZoom';
        global.document.body.appendChild(modalsContainer);
        global.document.body.appendChild(recognitionProfileZoom);
        global.document.body.appendChild(categoryZoom);  

After this is done you can expect values, and use the DOM elements normally.



来源:https://stackoverflow.com/questions/46057037/creating-html-elements-for-javascript-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!