javascript - 如何在 ReactJS/Typescript 应用程序中使用 Jest 测试 Class 内的公共异步函数
问题描述
typeof PayoutApi 类型上不存在属性“getUsersTotalPayout”
我的课:
import { bind } from 'decko';
import BaseApi from './Base';
import * as NS from './types';
class PayoutApi extends BaseApi {
@bind
public async getUsersTotalPayout(userId: string): Promise<number> {
const params: NS.IGetUsersTotalPayoutRequest = { userId };
const response = await this.actions.get<{ payout: number }>(
'/api/get-total-payout',
params,
);
return response.data.payout;
}
}
export default PayoutApi;
测试文件:
import PayoutApi from './LiquidityPool';
const endpoint = '/api/get-total-payout';
const userId = 'foo';
jest.mock(endpoint, () => ({
getUsersTotalPayout: jest.fn(() => Promise.resolve({ data: { payout: 100.21 } }))
}));
describe('API: getUsersTotalPayout', () => {
it('should make a request when we get images', () => {
// const testApi = new PayoutApi();
expect(PayoutApi.getUsersTotalPayout(userId)).toHaveBeenCalledWith(endpoint, 'GET');
});
});
出现该错误expect(PayoutApi.getUsersTotalPayout).toHaveBeenCalledWith(endpoint, 'GET');
解决方案
您当前正在尝试调用该类的方法。因为它不是
static
你应该首先实例化类的对象。let api = new PayoutApi(); expect(api.getUsersTotalPayout(userId).....)
由于
jest.mock
模拟模块不是端点或 XHR 请求,您的测试将尝试将实时请求发送到 /api/get-total-payout。为了处理它,需要知道您使用什么 XHR 包装器。说fetch()
有很好的包装器模拟器,并且像 axios 这样的库也有它们的等价物。至于测试本身。
expect
如果您调用方法并根据其结果进行操作,则它不起作用。它应该是必须调用服务器的运行方法,然后检查是否已使用有效参数调用模拟 XHR:api.getUsersTotalPayout(userId); expect(fetch_or_other_wrapper_for_mocking_xhr.get_last_request_method()).toEqual('get', endpoint, userId)
推荐阅读
- firebase - 如何管理firebase中的权限以允许不同的用户读取/更新/写入?
- python - 驱动程序关闭后杀死python脚本?(硒,蟒蛇)
- scala - Scala中的延迟分页(迭代器的流/迭代器?)
- java - 如何允许在 Room 中使用 varags?
- algorithm - 代码片段中流程命令重复了多少次?为什么?
- javascript - 清除输入是选择更改
- laravel - 如何从 Laravel 中的控制器向 Route 传递多个参数?(整数和 Varchar)
- scala - Akka-http 响应实体 5 分钟后未订阅
- python - 如何解析多个子组的 XML 嵌套值
- python - 是否有任何回归模型可以根据数据集值给我一个数学方程?