如何使用Jest模拟axios发布请求?

时间:2019-04-08 06:51:29

标签: reactjs post jestjs

我可以使用以下方法模拟获取请求:

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/constrainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

但是我该如何模拟发布请求?

1 个答案:

答案 0 :(得分:0)

我按如下方式使用MockAdapter中的axios-mock-adapter

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import requestGenerator, { API } from './httpClient';
// This sets the mock adapter on the default instance
const mock = new MockAdapter(API);

describe('Test for api calls', () => {
  it('Should test for postReq method for Location not reachable by car', async () => {
    const mockDirectionResponse = {
      status: 'failure',
      error: 'Location not accessible by car'
    };
    mock.onPost('/route/token').reply(200, mockDirectionResponse);
    const response = await requestGenerator.postReq('/route/token');
    expect(response.data).toEqual(mockDirectionResponse);
  });
});
相关问题