javascript - 监视在被拒绝的 promise 中调用的函数

标签 javascript reactjs promise jestjs sinon

我想监视一个函数来测试当一个 promise 被拒绝时这个函数是否在 catch block 中被调用。我的代码是这样的 react 组件

export class ResetPassword extends Component {
    handleSubmit = e => {
        e.preventDefault();

        this.props
            .resetPassword()
            .then(() => {
                this.props.history.push(LOGIN_PATH);
            })
            .catch(({ error }) => {
                this.props.displayErrorAlert('impossible to change password. You should ask for a new reset password link',6000);
            });
    };
}

这里我想测试函数displayErrorAlert是否被调用。我做了这个测试

it('validate form', () => {
    const resetPassword = () => {
        return Promise.reject({
            error: {
                response: {
                    data: {
                        errors: [
                            {
                                title: 'foo',
                            },
                        ],
                    },
                },
            },
        });
    };

    const displaySpy = sinon.spy();

    const wrapper = mount(
        <ResetPassword
            history={{}}
            resetPassword={resetPassword}
            displayErrorAlert={displaySpy}
        />
    );

    wrapper.instance().handleSubmit({
        preventDefault: () => {},
    });

    expect(displaySpy.calledOnce).toEqual(true);
});

spy 被调用但当然是异步的,所以我的测试总是失败。我想找到一种方法来测试该函数是否仅在调用 catch block 后才被调用,但我不知道该怎么做。

最佳答案

Sinon 为您提供处理 promise 时所需的一切,您可以使用 sinon.stub() 解决和拒绝 stub 的 promise。

const resetPassword = sinon.stub();
const displayErrorAlert = sinon.spy();
const preventDefault = sinon.spy();

const props = {
  resetPassword,
  displayErrorAlert,
  history: []
};

describe('Given a component', () => {
  let component;

  describe('when rendered', () => {
    beforeAll(() => {
      component = shallow(<ResetPassword {...props} />);
    });

    describe('and the form is submitted and there is an error reseting the password', () => {
      beforeAll(() => {
        resetPassword.rejects(new Error('Oops!'));
        component.find('button').simulate('click', { preventDefault });
      });

      it('should invoke the displayErrorAlert function', () => {
        expect(displayErrorAlert.calledOnce).toBeTruthy();
      });
    });
  });
});

关于javascript - 监视在被拒绝的 promise 中调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49564751/

相关文章:

node.js - Promise 上的 for 循环不遵循良好的输出顺序

javascript - 如何用 promise 关闭文件句柄?

javascript - 单击两个单选按钮后执行 JS 函数吗?

javascript - 类型错误 : undefined is not an object (evaluating '_this.props.auth(values.username, values.password).then' )

javascript - Undefined 不是评估 this.state 的对象。*

javascript - 如何在 React JS 中选择性地启用/禁用表格中的按钮?

node.js - 为什么此示例会抛出 UnhandledPromiseRejectionWarning?

javascript - svg 旋转,缩放和平移鼠标

javascript - React-testing-library:在组件的上下文中找不到 "store"

javascript - 计算产品评级