【问题标题】:React Jest: How do I mock an async API call that returns data?React Jest:如何模拟返回数据的异步 API 调用?
【发布时间】:2021-01-10 16:02:25
【问题描述】:

我正在尝试测试一个 React 表组件(它使用异步 API 调用来返回表数据),但无法弄清楚如何模拟 API 调用以满足我的 React 测试文件。我有一个模拟数据文件来提供模拟数据。 (我只包含了相关代码)。

模拟数据:

const mockRequestData = [
    {
        "email": "runner1@test.com",
        "firstName": "runner1",
        "lastName": "runner1"
    },
    {
        "email": "runner2@test.com",
        "firstName": "runner2",
        "lastName": "runner2"
    },
    {
        "email": "runner3@test.com",
        "firstName": "runner3",
        "lastName": "runner3"
    },
];

export const mockData = {
    mockData: mockRequestData,
};

apiCall 在自己的文件中:

const getAllAthletesSigningUp = async () => {
    let athletesSigningUp= [];

    const response = await returnGetResponse("/api/atheletesignup");
    if (response.status === 200) {
        return athletesSigningUp= (response.body);
    }
    return athletesSigningUp
};

export {getAllAthletesSigningUp};

runnerTable 应用:

 const [requests, setRequests] = useState([]);

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

    const apiResponse = async () => {
        return setRequests(await getAllAthletesSigningUp ())
    }


<div className={"table_content"}>
                {
                  requests.map((request, index) => {
                       return (
                          <>
                              <div key={index} className={"table_row"} data-testid={"tableRow"}>
                                  <p>{formatText(request.email)}</p>
                                  <p>{formatText(request.firstName)}</p>
                                  <p>{formatText(request.lastName)}</p>

【问题讨论】:

    标签: reactjs user-interface async-await jestjs


    【解决方案1】:

    你可以使用jest.mock():

    jest.mock(<path to getAllAthletesSigningUp>, () => ({
      getAllAthletesSigningUp: jest.fn(() => [<mock data>])
    }))
    
    describe('...', () => {
      it('...', () => {
        // const {getAllAthletesSigningUp} = jest.requireMock(<path>) - if You need mocked implementation in test;
        // const {getAllAthletesSigningUp} = jest.requireActual(<path>) - if You need original implementation in test;
      })
    })
    

    或在单个测试中直接使用mockImplementationmockImplementationOnce() 描述实现:

    jest.mock(<path to getAllAthletesSigningUp>, () => ({
      getAllAthletesSigningUp: jest.fn()
    }))
    
    describe('...', () => {
      it('...', () => {
        const {getAllAthletesSigningUp} = jest.requireMock(<path>)
        // getAllAthletesSigningUp.mockImplementation(() => [<mock data>]) - for all function calls;
        // getAllAthletesSigningUp.mockImplementationOnce(() => [<mock data>]) - for single function call;
      })
    })
    

    【讨论】:

    • 我尝试了您的第二个选项,但我收到此错误:属性 'mockImplementationOnce' 在类型 '() => Promise' 上不存在。
    猜你喜欢
    • 2019-01-23
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2020-08-15
    • 2019-03-13
    • 1970-01-01
    相关资源
    最近更新 更多