首页 > 解决方案 > 如何在 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');

标签: javascriptreactjstypescriptclassjestjs

解决方案


  1. 您当前正在尝试调用该类的方法。因为它不是static你应该首先实例化类的对象。

    let api = new PayoutApi();
    expect(api.getUsersTotalPayout(userId).....)
    
  2. 由于jest.mock模拟模块不是端点或 XHR 请求,您的测试将尝试将实时请求发送到 /api/get-total-payout。为了处理它,需要知道您使用什么 XHR 包装器。说fetch()很好的包装器模拟器,并且像 axios 这样的库也有它们的等价物。

  3. 至于测试本身。expect如果您调用方法并根据其结果进行操作,则它不起作用。它应该是必须调用服务器的运行方法,然后检查是否已使用有效参数调用模拟 XHR:

    api.getUsersTotalPayout(userId);
    expect(fetch_or_other_wrapper_for_mocking_xhr.get_last_request_method()).toEqual('get', endpoint, userId)
    

推荐阅读