簡體   English   中英

React 應用程序測試,如何使用 Jest 測試 axios 發布請求?

[英]React app testing, how to test an axios post request with Jest?

App.js 看起來像這樣,我將如何用玩笑來測試它?

 

    handleClick = e => {
        axios
          .post(
            "https://api.openweathermap.org/data/2.5/weather?q=" +
              this.state.term +
              "&units=metric&appid=" +
              ApiKey
             
          ){...}

我知道我必須創建一個 mocking axios 文件,然后像這樣測試它,但它在主 App.js 中使用 setState。 我只想開玩笑地測試獲取請求/axios 帖子。

只需返回 axios 的 promise 代碼檢查下面的代碼片段

    // apiActions.js
    const axios = require('axios');
    
    // your api code goes here
    const fetchData = () => {
      return axios
        .get('https://jsonplaceholder.typicode.com/sample_url')
        .then(response => {
          return response.data;
        });
    };

    exports.fetchData = fetchData;

    // testSuit.js
    import fetchData from './apiActions.js';
    // your testing code goes here
    test('testing api call', () => {
    const sampleObj = {name:'',age:39....}
    fetchData().then(resp => {
      expect(resp).toMatchObject(sampleObj)
    })




        

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM