Test with reactjs renderIntoDocument keep failed due to required DOM

前端 未结 2 1910
梦如初夏
梦如初夏 2021-02-05 16:03

I am new to reactJS and try to learn how to test with it. I have encouter the following testing util method. However i am keep getting the same error message:ReferenceErro

2条回答
  •  难免孤独
    2021-02-05 16:24

    tl;dr; You need jsdom + Mocha.


    According to spec ReactTestUtils#renderIntoDocument,

    renderIntoDocument() requires a DOM:

    You will need to have window, window.document and window.document.createElement globally available before you import React. Otherwise React will think it can't access the DOM and methods like setState won't work.

    Traditionally, Unit testing in React is done using Jest, which apparently contains DOM support. And Mocha doesn't.

    To understand this, consider this overly simplify analogy, Jest = Mocha + jsdom.

    jsdom is implemented in JavaScript, we can have a DOM-like API to work with without needing a browser. That means that we don’t have to capture a browser in order test, like Karma (which is why it works the moment you use Karma). Hence, we can run our tests in environments without browsers, like in Node or in continuous integration environments.


    References:

    1. Tutorial: Testing React on Jsdom
    2. React Spec: ReactTestUtils#renderIntoDocument
    3. Information: How to Jest
    4. Information: react-testing-mocha-jsdom

提交回复
热议问题