首页 > 解决方案 > 模拟返回承诺的组件方法

问题描述

我需要为以下原型方法创建单元测试validateAddress

import MyService from 'api/my-service';
import staticData from 'static-data';
import constants from 'utilities/constants';
import locale from 'api/locale-provider';

    const myService = new MyService();
    /**
     * @param {Object} values
     * @param {String} currency
     * @param {Object} userProfile
     * @returns {Promise<boolean>}
     */
    export const validateAddress = (
        values,
        currency,
        userProfile
    ) => {
        const countryCode = locale.getCountry();
        if (
            staticData.type === constants.BILLING_MANAGER &&
            (countryCode === 'CA' || countryCode === 'US')
        ) {
            const payload = makeAddressPayload({
                values,
                currency
            });

            return myService
                .postAddress(payload, userProfile)
                .then(() => {
                    return true;
                })
                .catch(() => {
                    return false;
                });
        }
        return true;
    };

    const makeAddressPayload = ({
       values,
       paymentProcessor,
       currency
    }) => ({
       ...
    });

有谁知道我如何模拟MyService类方法postAddress

class MyService {

    constructor(options = {}) {
       ...
    }

    postAddress(payload, userProfile) {
    let promise = authorizedFetchRequest(
            ...
        );

        promise = fetchTimeoutHandler(promise);
        return promise;
    }
}

export default MyService;

标签: reactjsjestjs

解决方案


对于您的情况,您可以使用mockImplementationOnce方法来模拟postAddress请求的响应。

作为测试的一部分,这就是你可以窥探它的方式,

it('should call postAddress', () => {
  jest.spyOn(MyService, 'postAddress').mockImplementationOnce(() => (
    ...expected response
  ));
});

推荐阅读