代码之家  ›  专栏  ›  技术社区  ›  Adeel Imran

Jest异步API模拟

  •  0
  • Adeel Imran  · 技术社区  · 6 年前

    我已经在堆栈溢出上搜索了这个问题,但是找不到任何类似于我的用例。

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

    1 回复  |  直到 6 年前
        1
  •  4
  •   Teneff    6 年前

    自从 onGetBookingList

    可以这样定义异步方法:

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

    或者您可以使用jest.fn()来重新发出承诺

    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);
    }
    

    working exmaple