0

I want to develop usign 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 litle WebApi project in .Net, this WebApi has an endpoint wich 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 dont know if the Reactjs test can call Apis.

this 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;
}
ernesto petit
  • 1,436
  • 1
  • 14
  • 19

1 Answers1

2

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.

Ming Soon
  • 998
  • 2
  • 11
  • 32