React JS: Testing async function usiing Jest is throwing error, "ReferenceError: regeneratorRuntime is not defined"

784 Views Asked by At

I am writing the unit tests/ integration tests for my React JS web application using Jest. The component I am testing is making an API call asynchronously. I am using this library, https://github.com/ctimmerm/axios-mock-adapter to mock the API request.

This is my component

import React, { useState, useEffect } from 'react';
import Axios from 'axios';

const ExampleList = (props) => {
    const [ list, setList ] = useState([ ])

    const fetchList = async () => {
        let response = await Axios.get("http://dummy.restapiexample.com/api/v1/employees")
        setList(response.data.data)
    }

    const renderList = () => {
        return list.map((item, index) => {
            return <li key={index}>{item.employee_name}</li>
        })
    }

    useEffect(() => {
        fetchList()
    }, [ ])

    return (
        <div>
            <ul>
                {renderList()}
            </ul>
        </div>
    )
}

export default ExampleList;

This is my test that is mocking the API request.

import React from 'react';
import {cleanup, fireEvent, render, screen, waitForElement} from '@testing-library/react';
import ExampleList from "../../src/components/ExampleList";
import MockAdapter from "axios-mock-adapter";
import Axios from 'axios';

test("ExampleList Component", async () => {
    // first mock the API request.
    let mock = new MockAdapter(Axios);
    mock.onGet("http://dummy.restapiexample.com/api/v1/employees")
        .reply(200, {
            "status":"success",
            "data":[
                {
                    "id":"1",
                    "employee_name":"Wai Yan Hein",
                    "employee_salary":"720800",
                    "employee_age":"61"
                }
            ]
        })

    let  { getByText } = render(<ExampleList />)

    const listData = await waitForElement(getByText("Wai Yan Hein"))
    expect(listData).toBeTruthy()
})

When I run the test, I am getting the following error.

 FAIL  tests/unit/ExampleList.test.js
  ● Test suite failed to run

    ReferenceError: regeneratorRuntime is not defined

       5 | import Axios from 'axios';
       6 |
    >  7 | test("ExampleList Component", async () => {
         |     ^
       8 |     // first mock the API request.
       9 |     let mock = new MockAdapter(Axios);
      10 |     mock.onGet("http://dummy.restapiexample.com/api/v1/employees")

      at Object.<anonymous> (tests/unit/ExampleList.test.js:7:5)

What is wrong with my code and how can I fix it?

0

There are 0 best solutions below