我们如何测试使用 Jest 获取 useEffect 内部的 React 组件?

问题描述 投票:0回答:1

我有以下组件,我需要为此编写一个测试。 如何模拟获取的数据,以便状态

fetchedEmbed
可以等于
mockModel
对象?

    type OembedResponse = {
      html: string;
      width: number;
      height: number;
    };

const mockModel = {
    "type": "rich",
    "version": "1.0",
    "title": "Überlegen Sie, eine Wärmepumpe einzubauen?",
    "provider_name": "Opinary",
    "provider_url": "https://www.opinary.com/",
    "author_name": "rtl",
    "cache_age": 10800,
    "html": "<div class=\"opinary-widget-embed\" data-poll=\"berlegen-sie-eine-wrmepumpe-einzubauen_r\" data-customer=\"rtl\" data-integration=\"oembed-widget\"></div>\n\t<script async type=\"text/javascript\" src=\"//widgets.opinary.com/embed.js\"></script>",
    "width": 500,
    "height": 500
  }

    export default function Embed({ model }: { readonly model: StorylineEmbedType }) {
      const [fetchedEmbed, setFetchedEmbed] = useState<OembedResponse>();

      useEffect(() => {
        fetch(`apiCall`)
          .then((res) => res.json())
          .then((data) => {
            data.html && setFetchedEmbed(data);
          });
        return () => {
          setFetchedEmbed(undefined);
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, []);

      return (
        <div className={styles.root}>
          {fetchedEmbed ? parse(`${fetchedEmbed.html}`) : <div className={styles.loading}></div>}
        </div>
      );
    }
reactjs jestjs
1个回答
0
投票

长话短说:使用 jest.spyOn 或 jest.mock

第一个选项是这样的:

beforeEach(() => {
  jest.spyOn(global, 'fetch').mockResolvedValue(mockModel);

afterAll(() => {
  jest.clearAllMocks()
})

所以,基本上你模拟了整个获取。 但我建议创建 api 类来发出 HTTP 请求并使用

jest.mock
模拟它,因为它可以让您更好地控制正在发生的事情。

© www.soinside.com 2019 - 2024. All rights reserved.