javascriptreactjsecmascript-6es6-promisereactjs-testutils

Reactjs Test api call


I want to develop using Reactjs, I made an App where I call an API (https://jsonplaceholder.typicode.com/users), also I made a test for this call and I couldn't call this API.

I made a little WebApi project in .Net, this WebApi has an endpoint which return me a JSON with this simple structure: {{person:1},{person:2}}. I tested this endpoint using postman and a breakpoint in Visual and it worked.

Now I want to use the test suite of React (I don't know if it is a test suite, mpn test), to call this endpoint but the test doesn't call the endpoint because the breakpoint in visual doesn't active, I don't know if the Reactjs test can call APIs.

these are the files:

PersonHelpers.test.js

import {checkPersonList} from './RobotHelpers';

test('Check person in list',() => {

    var result = false;
    result = checkPersonList();

    expect(result).toEqual(true);
});

PersonHelpers.js

export const checkPersonList = () => {
    var persontList = null;

    setTimeout(() => {
        fetch('http://localhost:23620/api/Values')
        .then(response => response.json())
        .then(data => {
            persontList = data;
        });
    },1000);

    console.log("list",persontList);
    if (persontList === null)
        console.log("is null")

    if((persontList != null) && (persontList.lenght > 0))
        return true;
    else
        return false;
}

Solution

  • What you want to test here is not the backend API you developed in .NET, but the checkPersonList() to behave correctly upon receiving API responses.

    AFAIK, for unit testing, you don't need to call the API directly, but mock up the API requests and responses.

    For that purpose, you can use the fetch-mock library.