How to set the width of a React component during test?

前端 未结 3 2006
隐瞒了意图╮
隐瞒了意图╮ 2021-02-19 05:23

I\'m trying to test a slider component. \"\"

This slider compone

3条回答
  •  囚心锁ツ
    2021-02-19 05:32

    I've been fighting the same problem myself today - I'm building a component that will scale its text size based on the size of the element. Because renderIntoDocument places your component inside a detached DOM node, it isn't possible to calculate offsetWidth, clientWidth, etc.

    Are you testing in a browser or node.js? (EDIT: I see you tagged the question PhantomJS so I'm guessing browser!) If you're in a browser you may be able to render the component into the DOM for real:

    React.render(, document.body);
    

    If you're worried about test isolation, you can create an IFrame to render the component into, and clean that up afterwards:

    beforeEach(function() {
        this.iframe = document.createElement('iframe');
        document.body.appendChild(this.iframe);
    });
    
    React.render(, this.iframe.contentDocument.body);
    
    afterEach(function() {
        document.body.removeChild(this.iframe);
    });
    

    Then call this.iframe.contentDocument.body.querySelectorAll('.track') to get the HTML Element and run your assertions against it (This is a plain HTML element, not a React component, so use the standard APIs to query it).

提交回复
热议问题