0

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;
}

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.