reactjs - 模拟返回承诺的组件方法
问题描述
我需要为以下原型方法创建单元测试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;
解决方案
对于您的情况,您可以使用mockImplementationOnce方法来模拟postAddress
请求的响应。
作为测试的一部分,这就是你可以窥探它的方式,
it('should call postAddress', () => {
jest.spyOn(MyService, 'postAddress').mockImplementationOnce(() => (
...expected response
));
});
推荐阅读
- javascript - 如何使用 for 循环为父级内部的许多 P 设置 ID?
- c# - C#为DataGridView组合SQL表添加Combobox和Checkbox
- php - laravel 中 boot 和 booted 的区别
- c# - 如何让 File.OpenText 返回不可为空的 StreamReader
- c++ - grpc c++ 的最佳包装器实现是什么?
- elasticsearch - 地理距离 - 弹性搜索
- c++ - 在 C++ Builder 中获取文本文件的第二行
- python-3.x - 使用 pandas 将 Numpy 数组转换为 Dataframe
- amazon-s3 - S3 中 spark.catalog.refreshTable(tablename) 的使用
- entity-framework - 开始使用带有 DB2 的实体框架