Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions frontend/__mocks__/styleMock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = {};
45 changes: 45 additions & 0 deletions frontend/__tests__/components/currency/CurrencyList.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import React from "react";
import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom";
import CurrencyList from "../../../components/currency/CurrencyList";
import { CurrencyInfo } from "../../../lib/api/currency";

const mockCurrencies: Record<string, CurrencyInfo> = {
INR: { countryName: "INDIA", currencyCode: "INR", currencyName: "Indian Rupees" },
USD: { countryName: "USA", currencyCode: "USD", currencyName: "US Dollars" },
};

describe("CurrencyList", () => {
it("renders currency table with all entries", () => {
render(<CurrencyList currencies={mockCurrencies} />);

expect(screen.getByText("Available Currencies")).toBeInTheDocument();
expect(screen.getByText("INR")).toBeInTheDocument();
expect(screen.getByText("Indian Rupees")).toBeInTheDocument();
expect(screen.getByText("INDIA")).toBeInTheDocument();
expect(screen.getByText("USD")).toBeInTheDocument();
expect(screen.getByText("US Dollars")).toBeInTheDocument();
expect(screen.getByText("USA")).toBeInTheDocument();
});

it("renders table headers", () => {
render(<CurrencyList currencies={mockCurrencies} />);

expect(screen.getByText("Currency Code")).toBeInTheDocument();
expect(screen.getByText("Currency Name")).toBeInTheDocument();
expect(screen.getByText("Country")).toBeInTheDocument();
});

it("shows message when no currencies available", () => {
render(<CurrencyList currencies={{}} />);

expect(screen.getByText("No currencies available.")).toBeInTheDocument();
});

it("renders correct number of rows", () => {
render(<CurrencyList currencies={mockCurrencies} />);

const rows = screen.getAllByTestId(/currency-row-/);
expect(rows).toHaveLength(2);
});
});
104 changes: 104 additions & 0 deletions frontend/__tests__/components/currency/ExchangeRateCalculator.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom";
import ExchangeRateCalculator from "../../../components/currency/ExchangeRateCalculator";
import { CurrencyInfo } from "../../../lib/api/currency";
import * as currencyApi from "../../../lib/api/currency";

const mockCurrencies: Record<string, CurrencyInfo> = {
INR: { countryName: "INDIA", currencyCode: "INR", currencyName: "Indian Rupees" },
USD: { countryName: "USA", currencyCode: "USD", currencyName: "US Dollars" },
CAD: { countryName: "CANADA", currencyCode: "CAD", currencyName: "Canadian Dollars" },
};

jest.mock("../../../lib/api/currency", () => ({
...jest.requireActual("../../../lib/api/currency"),
fetchExchangeRate: jest.fn(),
}));

describe("ExchangeRateCalculator", () => {
beforeEach(() => {
jest.clearAllMocks();
});

it("renders form with currency dropdowns", () => {
render(<ExchangeRateCalculator currencies={mockCurrencies} />);

expect(screen.getByText("Exchange Rate Calculator")).toBeInTheDocument();
expect(screen.getByTestId("from-currency-select")).toBeInTheDocument();
expect(screen.getByTestId("to-currency-select")).toBeInTheDocument();
expect(screen.getByTestId("calculate-btn")).toBeInTheDocument();
});

it("shows error when currencies not selected", async () => {
render(<ExchangeRateCalculator currencies={mockCurrencies} />);

fireEvent.click(screen.getByTestId("calculate-btn"));

expect(screen.getByTestId("error-message")).toHaveTextContent(
"Please select both currencies."
);
});

it("shows error when same currency selected", async () => {
render(<ExchangeRateCalculator currencies={mockCurrencies} />);

fireEvent.change(screen.getByTestId("from-currency-select"), {
target: { value: "USD" },
});
fireEvent.change(screen.getByTestId("to-currency-select"), {
target: { value: "USD" },
});
fireEvent.click(screen.getByTestId("calculate-btn"));

expect(screen.getByTestId("error-message")).toHaveTextContent(
"Please select different currencies."
);
});

it("displays exchange rate result on success", async () => {
(currencyApi.fetchExchangeRate as jest.Mock).mockResolvedValue({
fromCurrencyCode: "USD",
toCurrencyCode: "INR",
exchangeRate: "80.08",
});

render(<ExchangeRateCalculator currencies={mockCurrencies} />);

fireEvent.change(screen.getByTestId("from-currency-select"), {
target: { value: "USD" },
});
fireEvent.change(screen.getByTestId("to-currency-select"), {
target: { value: "INR" },
});
fireEvent.click(screen.getByTestId("calculate-btn"));

await waitFor(() => {
expect(screen.getByTestId("exchange-result")).toHaveTextContent(
"1 USD = 80.08 INR"
);
});
});

it("displays error when exchange rate not found", async () => {
(currencyApi.fetchExchangeRate as jest.Mock).mockRejectedValue(
new Error("Not found")
);

render(<ExchangeRateCalculator currencies={mockCurrencies} />);

fireEvent.change(screen.getByTestId("from-currency-select"), {
target: { value: "USD" },
});
fireEvent.change(screen.getByTestId("to-currency-select"), {
target: { value: "CAD" },
});
fireEvent.click(screen.getByTestId("calculate-btn"));

await waitFor(() => {
expect(screen.getByTestId("error-message")).toHaveTextContent(
"Exchange rate not found for the selected pair."
);
});
});
});
7 changes: 7 additions & 0 deletions frontend/babel.jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
presets: [
["@babel/preset-env", { targets: { node: "current" } }],
["@babel/preset-react", { runtime: "classic" }],
"@babel/preset-typescript",
],
};
43 changes: 43 additions & 0 deletions frontend/components/currency/CurrencyList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import React from "react";
import { CurrencyInfo } from "../../lib/api/currency";

interface CurrencyListProps {
currencies: Record<string, CurrencyInfo>;
}

/**
* Displays all available currencies in a table format.
*/
const CurrencyList: React.FC<CurrencyListProps> = ({ currencies }) => {
const entries = Object.entries(currencies);

if (entries.length === 0) {
return <p>No currencies available.</p>;
}

return (
<div className="currency-list">
<h2>Available Currencies</h2>
<table className="table table-striped" style={{ width: "100%" }}>
<thead>
<tr>
<th>Currency Code</th>
<th>Currency Name</th>
<th>Country</th>
</tr>
</thead>
<tbody>
{entries.map(([code, info]) => (
<tr key={code} data-testid={`currency-row-${code}`}>
<td>{info.currencyCode}</td>
<td>{info.currencyName}</td>
<td>{info.countryName}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};

export default CurrencyList;
120 changes: 120 additions & 0 deletions frontend/components/currency/ExchangeRateCalculator.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import React, { useState } from "react";
import {
CurrencyInfo,
ExchangeRateResponse,
fetchExchangeRate,
} from "../../lib/api/currency";

interface ExchangeRateCalculatorProps {
currencies: Record<string, CurrencyInfo>;
}

/**
* Provides a form to select two currencies and calculate the exchange rate.
*/
const ExchangeRateCalculator: React.FC<ExchangeRateCalculatorProps> = ({
currencies,
}) => {
const [fromCurrency, setFromCurrency] = useState("");
const [toCurrency, setToCurrency] = useState("");
const [result, setResult] = useState<ExchangeRateResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);

const currencyCodes = Object.keys(currencies);

const handleCalculate = async () => {
if (!fromCurrency || !toCurrency) {
setError("Please select both currencies.");
setResult(null);
return;
}
if (fromCurrency === toCurrency) {
setError("Please select different currencies.");
setResult(null);
return;
}
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.

setLoading(true);
setError(null);
setResult(null);

try {
const data = await fetchExchangeRate(fromCurrency, toCurrency);
setResult(data);
} catch {
setError("Exchange rate not found for the selected pair.");
} finally {
setLoading(false);
}
};

return (
<div className="exchange-rate-calculator" style={{ marginTop: "2rem" }}>
<h2>Exchange Rate Calculator</h2>
<div className="row" style={{ marginBottom: "1rem" }}>
<div className="col-md-4">
<label htmlFor="fromCurrency">From Currency</label>
<select
id="fromCurrency"
className="form-control"
value={fromCurrency}
onChange={(e) => setFromCurrency(e.target.value)}
data-testid="from-currency-select"
>
<option value="">-- Select --</option>
{currencyCodes.map((code) => (
<option key={code} value={code}>
{code} - {currencies[code].currencyName}
</option>
))}
</select>
</div>
<div className="col-md-4">
<label htmlFor="toCurrency">To Currency</label>
<select
id="toCurrency"
className="form-control"
value={toCurrency}
onChange={(e) => setToCurrency(e.target.value)}
data-testid="to-currency-select"
>
<option value="">-- Select --</option>
{currencyCodes.map((code) => (
<option key={code} value={code}>
{code} - {currencies[code].currencyName}
</option>
))}
</select>
</div>
<div className="col-md-4" style={{ display: "flex", alignItems: "flex-end" }}>
<button
className="btn btn-primary"
onClick={handleCalculate}
disabled={loading}
data-testid="calculate-btn"
>
{loading ? "Calculating..." : "Get Exchange Rate"}
</button>
</div>
</div>

{error && (
<div className="alert alert-danger" role="alert" data-testid="error-message">
{error}
</div>
)}

{result && (
<div className="alert alert-success" role="alert" data-testid="exchange-result">
<strong>
1 {result.fromCurrencyCode} = {result.exchangeRate}{" "}
{result.toCurrencyCode}
</strong>
</div>
)}
</div>
);
};

export default ExchangeRateCalculator;
13 changes: 13 additions & 0 deletions frontend/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = {
testEnvironment: "jsdom",
moduleNameMapper: {
"\\.(css|less|scss|sass)$": "<rootDir>/__mocks__/styleMock.js",
},
testPathIgnorePatterns: ["/node_modules/", "/.next/"],
transform: {
"^.+\\.(ts|tsx|js|jsx)$": [
"babel-jest",
{ configFile: "./babel.jest.config.js" },
],
},
};
1 change: 1 addition & 0 deletions frontend/jest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import "@testing-library/jest-dom";
42 changes: 42 additions & 0 deletions frontend/lib/api/currency.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { SERVER_BASE_URL } from "../utils/constant";

export interface CurrencyInfo {
countryName: string;
currencyCode: string;
currencyName: string;
}

export interface ExchangeRateResponse {
fromCurrencyCode: string;
toCurrencyCode: string;
exchangeRate: string;
}

/**
* Fetches all available currencies from the API.
*/
export const fetchCurrencies = async (): Promise<
Record<string, CurrencyInfo>
> => {
const response = await fetch(`${SERVER_BASE_URL}/currency`);
if (!response.ok) {
throw new Error("Failed to fetch currencies");
}
return response.json();
};

/**
* Fetches the exchange rate between two currencies.
*/
export const fetchExchangeRate = async (
from: string,
to: string
): Promise<ExchangeRateResponse> => {
const response = await fetch(
`${SERVER_BASE_URL}/exchange-rate/${from}/${to}`
);
if (!response.ok) {
throw new Error("Exchange rate not found");
}
return response.json();
};
Loading
Loading