Jest 异步 API 模拟

阿迪尔·伊姆兰

我在 stack-overflow 上搜索了这个问题,但找不到任何与我的用例类似的东西。

我有这样的容器组件。

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;

我想BookingAPI.onGetBookingList用我的this.onGetBookingList方法进行测试

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

这是我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 调用的代码部分。

休息时间

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

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

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

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

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

或使用 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);
}

工作示例

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何模拟非异步方法以使用 Jest 抛出异常?

如何在nodejs中用jest模拟异步方法

反应组件内的 Jest 模拟异步调用

如何在Jest中模拟IntersectionObserver API?

用Jest模拟Fetch API的问题

为什么JEST模拟模块的异步函数不需要异步或断言或解析

Jest 模拟计时器没有按预期异步工作;如何让这个测试通过?

如何编写返回异步的 API 调用的简单模拟

通过模拟请求使用异步api调用测试组件

在React.js中使用Jest模拟Bing Maps API

Jest 中的 API 模拟后 useEffect 中的无限循环

如何在VueTestUtils / Jest中模拟Web API?

如何在Jest中使用axios模拟API调用?

在 React jest API 测试中未调用模拟函数且未解析或返回模拟值

模拟异步处理请求

如何模拟“异步”语句?

模拟异步方法

如何模拟异步搜索?

Jest 模拟 Knex 交易

用 Jest 模拟 dotenv

禁用Jest setTimeout模拟

如何扩展 Jest 模拟?

使用Jest模拟会导致“动作必须是普通对象。将自定义中间件用于异步动作”。

异步模拟不适用于Jest,是否有更好的方法或简单的方法如sinon.stub()

是否可以在没有jest.mock('module')的情况下在NodeJS中使用Jest模拟API调用?

如何使用Jest模拟模拟模块的方法?

如何模拟正在用Jest测试的React组件中进行的API调用

Typescript,在Redux操作中测试Api调用,在Enzyme,Jest中模拟类

如何模拟api以验证是否通过jest和fetch正确呈现