【问题标题】:Mock state in react snapshot test?反应快照测试中的模拟状态?
【发布时间】:2021-01-07 12:24:00
【问题描述】:

希尔,

我想完成以下快照测试,但我不知道如何传入页面呈现所需的状态。

test('test renders as per snapshot', () => {
        const state = {
            orderNumber: 1000000001,
            userID: 1234567,
          }
        const tree = renderer
            .create(<Order location={ state }></Order>)
            .toJSON();
        expect(tree).toMatchSnapshot();
    });

我收到此错误

 TypeError: Cannot read property 'orderNumber' of undefined
> 40 |       this.props.location.state.orderNumber;

有人可以告诉我如何将它传递给我的快照测试以使其不会失败吗?

【问题讨论】:

    标签: reactjs unit-testing snapshot react-testing-library


    【解决方案1】:

    您应该将组件作为&lt;Order location={{ state }}&gt;&lt;/Order&gt; 传递(注意额外的花括号),因为它等于&lt;Order location={{ state: state }}&gt;&lt;/Order&gt;

    在您的帖子中, 表示将state 作为“props”的变量传入,而this.props.location.state 将未定义,从而导致您的错误。

    【讨论】:

    • 啊,这么简单,但我花了很长时间寻找这个,非常感谢,这解决了我的问题。
    • 我想将值的状态设置为 null 。以下是我尝试过的方法,但状态值未更新。能否请你帮忙? test.only("render component", () =&gt; { const state = { storeTabSelected: null }; const component = ( &lt;HomePage state={state} /&gt; ); render(component); });
    【解决方案2】:

    您在状态对象中缺少状态,我认为重命名为“位置”更有意义:

    test('test renders as per snapshot', () => {
            const location = {
                state: {
                  orderNumber: 1000000001,
                  userID: 1234567,
                }
              }
            const tree = renderer
                .create(<Order location={ location }></Order>)
                .toJSON();
            expect(tree).toMatchSnapshot();
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 2020-01-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多