首页 > 解决方案 > 如何在 Jest 中模拟 Promise 解析函数

问题描述

我正在使用 Jest + Enzyme。我有一个功能,

     submitHandler = values => {
         return new Promise((resolve, _) => {
                saveSomething({values, resolve});
         }
     }

我的测试:

    it('Should call saveSomething on form submit', () => {
        const values = {firstName: 'FName', lastname: 'LName'};
        const {enzymeWrapper, props} = setup();
        enzymeWrapper.find('Formik').simulate('submit', values);
        expect(props.saveSomething).toBeCalledWith({
            values: {
                ...values,
                contactLanguage: LOCALE_TO_LANGUAGE_MAP[props.locale],
            },
        });
    });

目前,我的测试失败了。错误:

    Error: expect(jest.fn()).toBeCalledWith(...expected)

    - Expected
    + Received

    @@ -1,6 +1,7 @@
      Object {
    +   "resolve": [Function anonymous],
        "values": Object {
          "contactLanguage": "FRENCH",
          "firstName": "FName",
          "lastname": "LName",
        },,

问题:如何模拟解析功能?

标签: javascriptunit-testingjestjsenzyme

解决方案


Jest mocks have an inherent method to cope with Promise resolutions and rejections. Please refer to the Jest Mock API for details.

The mockResolvedValue method is used for this very purpose.

Just mock your submitHandler with a simple call to jest.fn() and add the mockResolvedValue method.

You can test rejections as well with the mockRejectValue method.


推荐阅读