【问题标题】:Jest Mocked data not loaded during test测试期间未加载 Jest Mocked 数据
【发布时间】:2021-10-30 01:27:27
【问题描述】:

我有一个组件可以从我为测试模拟的 API 加载数据,但由于测试找不到包含数据的元素,因此它没有加载。

组件:

import { useDispatch, useSelector } from "react-redux";
import { useState, useEffect, useCallback } from "react";

import { businessDataActions } from "../store/business-data";
import { fetchBusinessListing } from "../services/business-listing";

import styles from "../styles/BizCard.module.css";
import BizCardItem from "./BizCardItem";

  const BizCard = (props) => {
  const dispatch = useDispatch();  
  const [listing, setListing] = useState([]);  

  //load all listing
  const fetchListing = useCallback(async () => {
    dispatch(businessDataActions.setIsLoading({ isLoading: true }));    

    const ListingService = await fetchBusinessListing();
    if (ListingService.success) {
      setListing(ListingService.data);
    } else {
      dispatch(
        businessDataActions.setNotify({
          severity: "error",
          message: "Problem when fetching listing.",
          state: true,
        })
      );
    }
    dispatch(businessDataActions.setIsLoading({ isLoading: false }));
  }, []);

  useEffect(() => {
    fetchListing();    
  }, []);

  const businessList = listing.map((item) => (
    <BizCardItem
      key={item.key}
      id={item.id}
      name={item.name}
      shortDescription={item.shortDescription}
      imageUrl={item.imageUrl}
    />
  ));

  return (
    <div className={styles.grid} role="grid">
      {businessList}
    </div>
  );
};

测试文件:

const bizListing = [
  ...some fake data
];
jest.mock("../../services/business-listing", () => {
  return function fakeListing() {
    return { success: true, data: bizListing };
  }
});

afterEach(cleanup);

describe('BizCard', () => {
    test("loading listing", async () => {      
      useSession.mockReturnValueOnce([null, false]);      
      
      await act(async () => {render(        
          <BizCard />        
      )});      
      
      const itemGrid = await screen.findAllByRole("gridcell");
      expect(itemGrid).not.toHaveLength(0);
    });
});

服务/业务列表:

export const fetchBusinessListing = async() => {    
    try {      
      const response = await fetch(
        "/api/business"
      );
      if (!response.ok) {
        throw new Error('Something went wrong!');
      }
      const data = await response.json();
      const loadedBusiness = [];
      
      for (const key in data) {
        let imgUrl =
          data[key].imageUrl !== "undefined" && data[key].imageUrl !== ""
            ? data[key].imageUrl
            : '/no-image.png';
            
          loadedBusiness.push({
            key: data[key]._id,
            id: data[key]._id,
            name: data[key].businessName,
            shortDescription: data[key].shortDescription,
            imageUrl: imgUrl,            
          });
      }      
      return { success: true, data: loadedBusiness };  
    } catch (error) {
      return ({success: false, message: error.message});
    }
}

使用这些返回执行的测试:

TypeError: (0 , _businessListing.fetchBusinessListing) is not a function

      48 |     // }
      49 |     
    > 50 |     const ListingService = await fetchBusinessListing();

    Unable to find role="gridcell"

当我使用浏览器时,我可以确认网格单元已呈现。 谁能解释一下我的问题

【问题讨论】:

  • 您能否分享一下您的../services/business-listing 文件中的内容?
  • 嗨@juliomalves,在上面添加了../services/business-listing。谢谢

标签: reactjs unit-testing jestjs next.js


【解决方案1】:

设法自己解决问题,问题在于模拟:

jest.mock("../../services/business-listing", () => {
    return {
        fetchBusinessListing: jest.fn(() => { return { success: true, data: bizListing }}),
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-21
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 2020-10-23
    相关资源
    最近更新 更多