Skip to content

Commit

Permalink
added test files
Browse files Browse the repository at this point in the history
  • Loading branch information
vuvnguyen95 committed Apr 22, 2024
1 parent da5f885 commit 9c91bb2
Show file tree
Hide file tree
Showing 5 changed files with 334 additions and 60 deletions.
2 changes: 2 additions & 0 deletions components/AddTask.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ const CreateTaskScreen = ({ route }) => {
selectedValue={priority}
onValueChange={(itemValue, itemIndex) => setPriority(itemValue)}
style={styles.priorityPicker}
testID="priority-selector"
>
<Picker.Item label="Low" value="low" />
<Picker.Item label="Medium" value="medium" />
Expand All @@ -88,6 +89,7 @@ const CreateTaskScreen = ({ route }) => {
onPress={handleCreateTask}
label="Create Task"
disabled={!taskName.trim()}
testID="create-task-button"
/>
</ScrollView>
);
Expand Down
4 changes: 3 additions & 1 deletion screens/SettingsScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,14 @@ function SelectProfile() {
placeholder={firstName ? firstName : 'John'}
placeholderTextColor={'#999897'}
onChangeText={(text) => setEditedFirstName(text)}
testID='first-name-input'
/>
<TextInput
style={{ ...styles.modalInput, flex: 1 }}
placeholder={lastName ? lastName : 'Doe'}
placeholderTextColor={'#999897'}
onChangeText={(text) => setEditedLastName(text)}
testID='last-name-input'
/>
</View>
<TextInput
Expand Down Expand Up @@ -194,7 +196,7 @@ function SelectProfile() {
keyboardType={"number-pad"}
/>
<View style={styles.modalButtonContainer}>
<TouchableOpacity style={styles.modalSaveButton} onPress={handleSaveChanges} >
<TouchableOpacity style={styles.modalSaveButton} onPress={handleSaveChanges} testID='save-button'>
<Text style={styles.modalText}>Save</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.modalCancelButton} onPress={closeModal} testID='cancel-button' >
Expand Down
107 changes: 107 additions & 0 deletions tests/AddMeal.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import React from "react";
import { render, fireEvent, waitFor } from "@testing-library/react-native";
import AddMeal from "../components/AddMeal"; // Updated to AddMeal
import { Alert } from "react-native";
import { useNavigation, useRoute } from "@react-navigation/native";
import { useMeals } from "../services/MealsContext";

// Mock useMeals to return default values and a function to update these values
jest.mock("../services/MealsContext", () => ({
useMeals: () => ({
savedMeals: [], // Default empty array for saved meals
setSavedMeals: jest.fn(), // Mock function to simulate setting saved meals
}),
}));

describe("AddMeal", () => {
});
jest.mock("@react-navigation/native", () => ({
...jest.requireActual("@react-navigation/native"),
useNavigation: jest.fn(() => ({
navigate: jest.fn(),
goBack: jest.fn(),
})),
useRoute: () => ({
params: { userID: "123" },
}),
}));

// Assuming similar dependencies for AddMeal as AddTask
jest.mock("../services/AuthAPI", () => ({
addMealData: jest.fn().mockResolvedValue(), // Assume this method handles meal data
}));

jest.mock("react-native", () => {
const actualRN = jest.requireActual("react-native");
return {
...actualRN,
Alert: {
...actualRN.Alert,
alert: jest.fn(),
},
};
});

jest.mock("../components/CreateButton", () => "CreateButton");
jest.mock("../components/MealHeader", () => "MealHeader");

jest.mock("../services/ThemeContext", () => ({
useTheme: () => ({
theme: "light",
toggleTheme: jest.fn(),
}),
}));

describe("AddMeal", () => {
const mockNavigate = jest.fn();
const mockGoBack = jest.fn();

beforeEach(() => {
jest.clearAllMocks();
jest.resetAllMocks();

useNavigation.mockReturnValue({
navigate: mockNavigate,
goBack: mockGoBack,
});
});

it("renders correctly with initial route params", () => {
const route = { params: { userID: "123" } };
const { getByPlaceholderText } = render(<AddMeal route={route} />);
expect(getByPlaceholderText("Meal Name")).toBeTruthy(); // Adjusted placeholder
});

it("handles input changes", () => {
const route = { params: { userID: "123" } };
const { getByPlaceholderText } = render(<AddMeal route={route} />);
const nameInput = getByPlaceholderText("Meal Name"); // Adjusted placeholder
fireEvent.changeText(nameInput, "New Meal");
expect(nameInput.props.value).toBe("New Meal");
});

it("adds a new meal and updates state correctly", async () => {
const { getByPlaceholderText, getByTestId } = render(<AddMeal route={{ params: { userID: "123" } }} />);
const mealNameInput = getByPlaceholderText("Meal Name");
const createButton = getByTestId("submit-meal");
fireEvent.changeText(getByPlaceholderText("Meal Name"), "Pasta");
fireEvent.changeText(getByPlaceholderText("Add ingredients..."), "Tomato, Cheese");
fireEvent.changeText(getByPlaceholderText("Servings"), "4");
fireEvent.changeText(getByPlaceholderText("Add instructions..."), "Cook for 20 minutes");

// Simulate button press
fireEvent.press(createButton);

await waitFor(() => {
// Check if the Alert was called with the correct arguments
expect(Alert.alert).toHaveBeenCalledWith("Confirm", expect.anything(), expect.anything());
// Simulate user confirming the creation
const confirmButton = Alert.alert.mock.calls[0][2][1].onPress;
confirmButton();
});

// Check if navigation was called after adding the meal
expect(mockNavigate).toHaveBeenCalledWith("Your Cookbook", { activeTab: "SavedMeals" });
});

});
126 changes: 126 additions & 0 deletions tests/CreateTaskScreen.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import React from "react";
import { render, fireEvent, waitFor } from "@testing-library/react-native";
import AddTask from "../components/AddTask";
import { Alert } from "react-native";
import { useNavigation, useRoute } from "@react-navigation/native";

// Ensuring consistent mock returns for every test instance
jest.mock("@react-navigation/native", () => ({
...jest.requireActual("@react-navigation/native"),
useNavigation: jest.fn(() => ({
navigate: jest.fn(),
goBack: jest.fn(),
})),
useRoute: () => ({
params: { userID: "123" },
}),
}));

// Mock Firebase and navigation
jest.mock("firebase/auth", () => {
return {
getAuth: jest.fn(() => ({
currentUser: { uid: "123" },
signOut: jest.fn().mockResolvedValue(),
})),
};
});

jest.mock("firebase/firestore", () => {
return {
getFirestore: jest.fn(),
doc: jest.fn(() => ({
get: jest.fn(() =>
Promise.resolve({
data: () => ({
firstName: "John",
lastName: "Doe",
phone_number: "1234567890",
}),
})
),
})),
getDoc: jest.fn(() =>
Promise.resolve({
exists: () => true,
data: () => ({ firstName: "John", lastName: "Doe" }),
})
),
};
});

jest.mock("../services/AuthAPI", () => ({
saveTaskForUser: jest.fn().mockResolvedValue(),
}));

jest.mock("react-native", () => {
const actualRN = jest.requireActual("react-native");
return {
...actualRN,
Alert: {
...actualRN.Alert,
alert: jest.fn(),
},
};
});

jest.mock("../components/DateTimePicker", () => "DateTimePicker");
jest.mock("../components/TypeSelector", () => "TypeSelector");
jest.mock("../components/CreateButton", () => "CreateButton");

jest.mock("../services/ThemeContext", () => ({
useTheme: () => ({
theme: "light",
toggleTheme: jest.fn(),
}),
}));

describe("AddTask", () => {
const mockNavigate = jest.fn();
const mockGoBack = jest.fn();

beforeEach(() => {
jest.clearAllMocks();
jest.resetAllMocks();

// Mock useNavigation with specific implementations for each test
useNavigation.mockReturnValue({
navigate: mockNavigate,
goBack: mockGoBack,
});
});

it("renders correctly with initial route params", () => {
const route = { params: { userID: "123" } };
const { getByPlaceholderText } = render(<AddTask route={route} />);
expect(getByPlaceholderText("Name")).toBeTruthy();
});

it("handles input changes", () => {
const route = { params: { userID: "123" } };
const { getByPlaceholderText } = render(<AddTask route={route} />);
const nameInput = getByPlaceholderText("Name");
fireEvent.changeText(nameInput, "New Task");
expect(nameInput.props.value).toBe("New Task");
});

it("calls the save task API and navigates on successful task creation", async () => {
const route = { params: { userID: "123" } };
const { getByTestId, getByPlaceholderText } = render(<AddTask route={route} />);
const nameInput = getByPlaceholderText("Name");
fireEvent.changeText(nameInput, "New Task");
fireEvent.changeText(getByPlaceholderText("Location"), "Home");
fireEvent.changeText(getByPlaceholderText("Comments"), "Test comment");
fireEvent.changeText(getByTestId("priority-selector"), "high");
fireEvent.press(getByTestId("create-task-button"));

await waitFor(() => {
expect(Alert.alert).toHaveBeenCalledWith(
"Success", "Task created successfully!"
);
});


});

});
Loading

0 comments on commit 9c91bb2

Please sign in to comment.