【问题标题】:React testing with Enzyme, componentDidMount updating HTML()使用 Enzyme 进行 React 测试,componentDidMount 更新 HTML()
【发布时间】:2020-11-25 11:33:50
【问题描述】:

假设我们有一个组件

import React, { Component } from "react";
import $                  from "jquery";
class App extends Component {

    componentDidMount() {
        $('#empty_p_tag').text('hello')
    }

    render() {
        return (
            <div>
                <p>This is a component</p>
                <p id ="empty_p_tag"></p>
            </div>)
    }
}
export default App;


我们想要测试带有 id empty_p_tag 的 p 标签现在在标签中说“你好”。我们如何用酶和玩笑做到这一点?

it('should render hello', function () {
    const app_wrapper = mount(<App/>);
    const p_tag = app_wrapper.find('#empty_p_tag').text();
    expect(p_tag).toBe('hello');

});

运行此测试时,我得到了响应:

    expect(received).toBe(expected) // Object.is equality

    Expected: "hello"
    Received: ""

      4 |       const app_wrapper = mount(<App/>);
      5 |       const p_tag = app_wrapper.find('#empty_p_tag').text();
    > 6 |       expect(p_tag).toBe('hello');
        |                     ^
      7 | 
      8 | });


我不确定我在哪里做错了?我应该将 p_tag 元素存储在构造函数的 props 和 states 部分吗?此外,我试图避免使用 mount,但是当我使用浅层运行时,它并不快乐。

感谢您的帮助

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    Ciao,如herecomponentDidMount 所述,在挂载后运行。不仅如此,根据this 的帖子,直接操作 DOM 是反应中的反模式。相反,您可以使用stateHere 一个工作示例。

    我所做的是在state 组件中定义一个text。然后,在componentDidMount 上,我调用this.setStatetext 设置为hello

    所以,你的组件变成:

    class App extends Component {
        constructor(props) {
          super(props);
          this.state = {
             text: ""
          };
         }
    
        componentDidMount() {
            this.setState({ text: "hello" });
        }
    
        render() {
            return (
                <div>
                    <p>This is a component</p>
                    <p id ="empty_p_tag">{this.state.text}</p>
                </div>)
        }
    }
    export default App;
    

    你的测试变成:

    it('should check `componentDidMount()`', () => {
          const app_wrapper = mount(<TestComponent />);
          const p_tag = app_wrapper.find("#empty_p_tag").text();
          expect(p_tag).toBe("hello");
    });
    

    【讨论】:

    • 您好,感谢您的回复。不幸的是,这不起作用。我仍然得到相同的结果。我看过你说的链接,它已经过时了。您认为我应该将这些信息存储在应用程序构造函数中吗?感谢您的帮助
    • Ciao,抱歉回答晚了,但今天是非常忙碌的一天。我尝试更好地重写我的答案。
    • 谢谢 :) 这就是我所做的。感谢您的确认。
    • 没问题,很抱歉我之前的错误。祝你有美好的一天:)
    猜你喜欢
    • 2018-08-31
    • 2016-11-13
    • 2018-12-23
    • 1970-01-01
    • 2019-03-18
    • 2021-04-14
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多