The TestCaseCreator component is a reusable UI component that allows users to create new test cases. It includes:
- A dropdown for selecting test case types (Manual, Automated, BDD)
- An input field for entering the test case title
- A Create button that triggers the API call
- Type Dropdown: Allows selection of test case type
- Title Input: Text input for test case title with placeholder text
- Create Button: Submits the form and creates a new test case
- Loading States: Button shows "Creating..." while API call is in progress
- Form Validation: Prevents submission if title is empty
- Keyboard Support: Enter key submits the form
- Mobile-friendly layout that stacks vertically on smaller screens
- Proper focus states and accessibility
The current implementation uses a mock API located in src/api/testCasesAPI.js.
// Create test case function
createTestCase: async ({ title, type, template, priority, status }) => {
// Simulates network delay (200-1000ms)
await new Promise((resolve) =>
setTimeout(resolve, Math.random() * 800 + 200)
);
// Simulates 5% chance of API error
if (Math.random() < 0.05) {
throw new Error("Failed to create test case. Please try again.");
}
// Creates a new test case object with generated ID
const newTestCase = {
id: `tc-${newId}`,
identifier: `TC-${String(newId).padStart(3, "0")}`,
name: title,
priority:
priorities.find((p) => p.internal_name === priority) || priorities[1],
owner: "Current User",
status: statuses.find((s) => s.internal_name === status) || statuses[2],
tags: type === "BDD" ? ["BDD", "Automated"] : [type],
template: template || "test_case_steps",
automationStatus:
type === "Automated"
? "Automated"
: type === "BDD"
? "Semi-Automated"
: "Manual",
createdDate: new Date(),
lastModified: new Date(),
};
// Adds to mock data array
mockTestCases.unshift(newTestCase);
return newTestCase;
};To replace the mock implementation with a real API, follow these steps:
Replace the createTestCase function in src/api/testCasesAPI.js:
createTestCase: async ({ title, type, template, priority, status }) => {
try {
const response = await fetch("/api/testcases", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${getAuthToken()}`, // Add authentication if needed
},
body: JSON.stringify({
name: title,
type: type,
template: template,
priority: priority,
status: status,
// Add other required fields based on your API schema
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
throw new Error(`Failed to create test case: ${error.message}`);
}
};Replace /api/testcases with your actual API endpoint URL.
Add authentication headers if your API requires them:
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
'X-API-Key': 'your-api-key', // If using API key authentication
}Map the component data to your API's expected format:
body: JSON.stringify({
// Map component fields to API fields
title: title, // or "name": title
testCaseType: type, // or "type": type
templateType: template, // or "template": template
priorityLevel: priority, // or "priority": priority
currentStatus: status, // or "status": status
// Add any additional required fields
projectId: getCurrentProjectId(),
createdBy: getCurrentUserId(),
});Ensure the API response is properly formatted for the Redux store:
// If your API returns a different structure, transform it:
const transformApiResponse = (apiResponse) => ({
id: apiResponse.testCaseId,
identifier: apiResponse.testCaseNumber,
name: apiResponse.title,
priority: {
internal_name: apiResponse.priority.toLowerCase(),
name: apiResponse.priority,
},
status: {
internal_name: apiResponse.status.toLowerCase(),
name: apiResponse.status,
},
// Transform other fields as needed
});
return transformApiResponse(data);Update error handling to match your API's error format:
catch (error) {
// Handle different types of errors
if (error.name === 'AbortError') {
throw new Error('Request was cancelled');
} else if (error.response) {
// API responded with error status
throw new Error(error.response.data.message || 'Failed to create test case');
} else {
// Network or other error
throw new Error('Network error. Please check your connection.');
}
}The component integrates with Redux through:
- Action:
createTestCaseasync thunk insrc/store/testCasesSlice.js - State Management: Handles loading states and updates the test cases list
- Automatic Refresh: New test cases are automatically added to the current view
Import and use the component:
import { TestCaseCreator } from "./components/TestCasesTable";
function App() {
return (
<div>
<TestCaseCreator />
{/* Other components */}
</div>
);
}The mock API includes:
- Random network delays (200-1000ms)
- 5% chance of simulated errors
- Automatic form reset on success
- Integration with existing test case list
This allows for comprehensive testing of:
- Loading states
- Error handling
- Success scenarios
- User experience flows