【问题标题】:Jest: "container does not exist"开玩笑:“容器不存在”
【发布时间】:2019-04-24 15:11:17
【问题描述】:

我有一个非常简单的测试

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

此代码失败:

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

错误:

● 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,

容器确实存在。

我认为这是一个常见问题,因为 ComponentDidMount 在渲染之前执行?

运行命令:

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

版本:

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

【问题讨论】:

    标签: reactjs jestjs babel-jest react-scripts


    【解决方案1】:

    经过很多痛苦后,我使用模拟解决了这个问题。

    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);
    });
    

    这通过了我的测试,尽管vs code 仍然抱怨

    mockImplementation 不存在于类型 () => void

    【讨论】:

      猜你喜欢
      • 2018-02-19
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 2020-11-22
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 2019-05-24
      相关资源
      最近更新 更多