Jest 异步 API 模拟 [英] Jest Asynchronous API Mocking

查看:23
本文介绍了Jest 异步 API 模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 stack-overflow 上搜索过这个问题,但没有找到与我的用例类似的东西.

I have searched this issue on stack-overflow, but couldn't find anything similar to me use case.

我有这样的容器组件.

import React, { Component } from 'react';
import PropTypes from 'prop-types';

// API
import BookingAPI from '../../../../api/BookingAPI';

class CustomerProfilePage extends Component {
  state = {
    list: [],
    totalRecords: 0,
    pageNo: 1,
  };

  componentDidMount() {
    const { pageNo } = this.state;
    this.onGetBookingList({ pageNo });
  }

  onGetBookingList = async ({ pageNo = 0 }) => {
    const { match } = this.props;
    try {
      const result = await BookingAPI.onGetBookingList({
        passengerId: match.params.customerId,
        sortProperties: ['id'],
        limitCount: 10,
        pageNo,
      });
      this.setState({
        list: result.items,
        totalRecords: result.totalRecords,
     });
    } catch (error) {
      // console.log('error is', error);
    }
  };

  render() {
    return <div></div>;
  }
}

export default CustomerProfilePage;

我想在我的 this.onGetBookingList 方法中测试 BookingAPI.onGetBookingList.

I want to test BookingAPI.onGetBookingList in my this.onGetBookingList method.

到目前为止,这是我尝试过的,我在这里遗漏了什么..

So far this is what I have tried, am I missing something here..

这是我下面的CustomerProfilePage.test.js 文件

import React from 'react';
import { shallow } from 'enzyme';

// Components
import CustomerProfilePage from './CustomerProfilePage';

function setup() {
  const props = {
     match: {
       params: {
         customerId: 1,
       },
     },
  };
  return shallow(<CustomerProfilePage {...props} />);
}

describe('CustomerProfilePage', () => {
  it('Should update state on onGetBookingList call', async () => {
    jest.mock('../../../../api/BookingAPI', () => ({
      onGetBookingList: () => {
        const data = { items: [{ value: 1 }, { value: 2 }], totalRecords: 1 };
        return jest.fn().mockReturnValue(data);
      },
    }));
    const wrapper = setup();
    await wrapper.instance().onGetBookingList({ pageNo: 1 });
    wrapper.update();
    expect(wrapper.state().totalRecords).toBe(1); // should be 1, but is 0
 });
});

为了简单起见,我没有在 render 中编写代码,因为我想专注于模拟 API 调用的代码部分.

For the purpose of simplicity I have not written the code in my render because I wanted to focus on the code part where I am mocking an API call.

推荐答案

因为 onGetBookingList 必须是一个异步函数

Since onGetBookingList has to be an async function

你可以像这样定义异步方法:

you can define async method like this:

jest.mock('../../../../api/BookingAPI', () => ({
    async onGetBookingList() {
        return data;
    }
}));

或者你可以使用 jest.fn() 返回一个 Promise

or you can use jest.fn() which retuns a Promise

jest.mock('../../../../api/BookingAPI', () => ({
    onGetBookingList: jest.fn(() => Promise.resolve(data))
}));

或者使用 jest.fn().mockResolvedValue()

or use jest.fn().mockResolvedValue()

jest.mock('../../../../api/BookingAPI', () => ({
    onGetBookingList: jest.fn().mockResolvedValue(data)
}));

然后

import { onGetBookingList } from '../../../../api/BookingAPI';

it('should be working with all of the above mocks', async () => {
    const { totalRecords } = await onGetBookingList();
    expect(totalRecords).toBe(1);
}

工作示例

这篇关于Jest 异步 API 模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆