【问题标题】:How to test a public async function inside Class using Jest in a ReactJS/Typescript app如何在 ReactJS/Typescript 应用程序中使用 Jest 测试 Class 内的公共异步函数
【发布时间】:2018-09-18 21:14:49
【问题描述】:

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'); 上收到该错误

【问题讨论】:

    标签: javascript reactjs typescript class jestjs


    【解决方案1】:
    1. 您当前正在尝试调用该类的方法。因为它不是static,所以你应该先实例化类的对象。

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      • 2019-03-04
      • 2018-03-24
      相关资源
      最近更新 更多