代码之家  ›  专栏  ›  技术社区  ›  larrydalmeida

如何测试不处理来自react测试库的带有“wait”的拒绝承诺的组件?

  •  0
  • larrydalmeida  · 技术社区  · 6 年前

    用户也可以选择订阅服务,但只有在下单成功时才应请求此订阅。

    为了测试这个失败的场景,我使用了承诺拒绝,但是未预料到的错误会冒出来,导致测试失败。

    catch 把链子拴在 onSubmit Confirmation 组件?做 开玩笑 wait 反应测试库

    我知道笑话提供 .rejects 但是我不知道我应该如何重组我的测试以使其与 .

    组成部分:

    class Confirmation extends React.Component {
      onSubmit() {
        const { createOrder, items, subscribeUser, userId } = this.props;
        createOrder({ items })
          .then(() => subscribeUser(userId));
          // no catch here because I use an error boundary component 
          // at the the top level of the App's component tree 
          // to catch and log all errors to a logging service
      }
      
      render() {
        return (
          <div>
            <input 
              type="submit" 
              onClick={this.onSubmit} 
              value="Confirm Order"
            />
          </div>
        )
      }
    }

    import React from 'react'
    import {
      render,
      fireEvent,
      wait
    } from 'react-testing-library'
    
    import Confirmation from './Confirmation'
    
    describe('Confirmation', () => {
    
      it("should not subscribe when the user's order creation fails", () => {
        const props = {
          userId: 12345,
          items: [{
            id: 121,
            qty: 1
          }, {
            id: 122,
            qty: 2
          }],
          createOrder: jest.fn(() => Promise.reject("Order creation failure")),
          subscribeUser: jest.fn(() => {})
        };
    
        const {
          container
        } = render( 
          <Confirmation { ...props } />
        );
    
        fireEvent.click(container.querySelector("#confirm-order"));
    
        return wait(() => {
          expect(props.createOrder).toHaveBeenCalledWith({
            items: props.items
          });
          expect(props.subscribeUser).not.toHaveBeenCalled();
        });
      });
    
    });

    请注意,上面的代码片段是不可执行的-实际上,组件比上面的示例复杂一些,但是我已经尽可能地简化了它,而没有歪曲问题。

    包装 <Confirmation/>

    Jest failure

    1 回复  |  直到 6 年前
        1
  •  0
  •   Ondrej Slinták    6 年前

    我将创建一个捕获错误并呈现错误的小组件:

    const onError = jest.fn()
    class Catcher extends React.Component {
      componentDidCatch(error, info) {
        onError(error, info)
      }
    
      render() {
        return this.props.children
      }
    }
    
    const { container } = render(
      <Catcher>
        <Confirmation { ...props } />
      </Catcher>
    );
    
    // After
    expect(onError).toHaveBeenCalledTimes(1)