简体   繁体   中英

Jest: “container does not exist”

I have a very simple test

    const div = document.createElement("div");
    ReactDOM.render(<App />, div);
    ReactDOM.unmountComponentAtNode(div);

fails on this code:

componentDidMount() {
    const ProgressBar = require('progressbar.js');
    /* istanbul ignore next */
    const bar = new ProgressBar.Line('#progressDiv', {
        strokeWidth: 2,
        easing: 'easeInOut',

error:

● renders without crashing

Container does not exist: #progressDiv

   6 |         const ProgressBar = require('progressbar.js');
   7 |         /* istanbul ignore next */
>  8 |         const bar = new ProgressBar.Line('#progressDiv', {
     |                     ^
   9 |             strokeWidth: 2,

container does exist.

I assume this is a common issue because ComponentDidMount executes before render?

run command:

npm test => "test": "react-scripts test --watchAll=false"

versions:

"react-scripts": {
  "version": "2.1.5",
  "jest": "23.6.0",

after much pain i solved this using a mock.

jest.mock('../components/app/App');

it("renders without crashing", () => {

    const spy = jest.fn()
    App.prototype.componentDidMount.mockImplementation(() => spy())

    const div = document.createElement("div");
    ReactDOM.render(<App />, div);
    ReactDOM.unmountComponentAtNode(div);
});

this passes my tests, although vs code still complains

mockImplementation does not exist on type () => void

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM