簡體   English   中英

如何為 React 無狀態功能組件模擬 api?

[英]How to mock an api for a React stateless functional component?

我正在嘗試測試在 useEffect 生命周期掛鈎期間進行 Fetch 調用的無狀態功能反應組件。 我想制作一個模擬 api 文件,該文件將在運行 Jest 單元測試時攔截此調用,但我沒有運氣嘗試實現這一點。

我的組件:App.js

import React, { useState, useEffect } from 'react';
import Form from './Form';
import Image from './Image';
import unsplash from '../services/unsplash';

function App() {
  const [deStat, setDeStat] = useState({
    term: '',
    images: [],
    status: 'initial'
  });

  const fetchImages = async term => {
    setDeStat({
      status: 'searching',
      term: term,
      images: []
    });

    try {
      const images = await unsplash(term);
      setDeStat({
        status: 'done',
        images
      });
    } catch (error) {
      setDeStat({
        status: 'error'
      });
    }
  };

  useEffect(() => {
    fetchImages('Mountains');
  }, []);

  return (
    <div className="App">
      <Form fetchImages={fetchImages} />

      {deStat.status === 'searching' && <h3>Searching for {deStat.term}</h3>}
      {deStat.status === 'done' && deStat.images.length === 0 && (
        <h3>
          Sorry sucker, no results{' '}
          <span role="img" aria-label="sad">
            😢
          </span>
        </h3>
      )}
      {deStat.status === 'error' && <h3>Oops... error!</h3>}

      <div className="images-container">
        <h5>Images okay!</h5>
        {deStat.images.map(image => (
          <Image image={image} key={image.id} />
        ))}
      </div>
    </div>
  );
}

export default App;

我的模擬服務( services/__mocks__/unsplash.js ):

const fakeData = [
  {
    id: 1,
    categories: [{ title: "Nice image" }],
    user: {
      name: "Mr. Photographer"
    },
    links: {
      html: "https://www.leighhalliday.com"
    },
    urls: {
      small: "https://www.image.com/nice.jpg"
    },
    likes: 10
  }
];

export default async term => {
  return await new Promise(resolve => {
    resolve(fakeData);
  });
};

我的測試(不工作,因為沒有調用模擬):

import App from './App';

jest.mock('../services/unsplash');

it('fetches images from unsplash and renders them on mount', done => {
  const wrapper = shallow(<App />);

  setTimeout(() => {
    console.log('inside timeout App2!');
    wrapper.update();

    expect(wrapper.find('Image').length).toEqual(1);

    done();
  });
});

誰能告訴我我在這里做錯了什么? 我想使用自定義 function 進行 fetch 調用而不是真正的調用。

您需要使用act()flush async events.

https://reactjs.org/docs/test-utils.html#act

也讓你的測試像這樣async

("should blah", async () => {}

同樣在您的模擬中,在async await中返回 promise 是多余的。 使用其中一種。

暫無
暫無

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

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