0

I have set up an api backend using FastAPI. Backend testing has been done already. But I don't know how to test the frontend correctly which is usign the api. Because I want at least one test that is performed via a real API request. The only problem is that my backend uses a database, and I haven't found a sensible way to replace this database connection with a fake database connection so that it doesn't accidentally remain active in production due to some error.

Currently I use Jest but since I haven't taken any tests yet, you can also recommend others to me.

My frontend function to test

export default async function createTodoAPI(name, description, accessToken) {
    const response = await fetch(`${import.meta.env.VITE_API_URL}/todo/create`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${accessToken}`
        },
        body: JSON.stringify({name: name, description: description})
    });

    if (!response.ok) {
        data = await response.json();
        throw new Error(data.detail || "Creation failed: An unexpected error is occurred.");
    };
}

What I tried, but somehow feel uncomfortable using:

import os
import sys
import logging

logger = logging.getLogger(__name__)

TEST_MODE: bool = os.getenv("TEST_MODE", "false").lower() == "true"
PRODUCTION: bool = os.getenv("IS_PRODUCTION", "false").lower() == "true"

# Defines the database url
if TEST_MODE and PRODUCTION:
    logger.error("\nTEST MODE COULD NOT BE ACTIVATED WHILE THE PRODUCTION IS ACTIVATED TOO.")
    sys.exit(1)
elif TEST_MODE:
    DB_URL = "sqlite+aiosqlite:///:memory:"
    logger.warning("\n\nTEST MODE IS ACTIVATED: Using in-memory database.\n\n")
else:
    DB_URL = os.getenv("DATABASE_URL")

1 Answer 1

0

When you talk about production and testing, then I would assume, you would maintain two seperate instances of your service side-by-side. One for testing and one for production. That's because you typically do not want to have to shut down your production application just for testing a new version.

So I would start two instances, one with TEST_MODE and one with PRODUCTION set. You could do that by running your python script twice, you'll probably want to create two batch files that first set the correct ENV variables and then run the frontend and backend scripts. Depending on those two ENV variables, you set a different database URL as well as a different frontend URL.

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.