Skip to content

Commit

Permalink
Merge pull request #544 from bounswe/feat-MB-unit-tests
Browse files Browse the repository at this point in the history
Feat mb unit tests
  • Loading branch information
furkansenkal authored Dec 16, 2024
2 parents 767d7fa + 19d970e commit 8bed908
Show file tree
Hide file tree
Showing 4 changed files with 259 additions and 3 deletions.
78 changes: 78 additions & 0 deletions mobile/__tests__/CreatePost.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import React from 'react';
import { render, fireEvent, waitFor } from '@testing-library/react-native';
import CreatePost from '../src/pages/CreatePost'; // Adjust the import as necessary
import { useAuth } from '../src/hooks/useAuth'; // Adjust the import path as necessary

// Mock useAuth hook
jest.mock('../src/hooks/useAuth', () => ({
useAuth: () => ({
accessToken: 'mockAccessToken', // Provide a default or mock value
userId: 'mockUserId',
}),
}));

jest.mock('node-fetch', () => require('jest-fetch-mock'));

describe('CreatePost Component', () => {

it('toggles tag selection', () => {
const { getByText, getByTestId } = render(<CreatePost />);

const tagChip = getByText('Tech'); // Assuming 'Tech' is the text of the tag chip
fireEvent.press(tagChip);

expect(getByText("Tech").props.style.backgroundColor).toBe("#007BFF");
});

it('creates a post successfully', async () => {
const postData = {
title: "Test Post Title",
content: "This is the content of the post.",
tags: ["Tech", "Science"]
};

fetch.mockResolvedValueOnce({
ok: true,
json: async () => postData,
});

const { getByPlaceholderText, getByText } = render(<CreatePost />);
const titleInput = getByPlaceholderText("Title");
const contentInput = getByPlaceholderText("Content...");

fireEvent.changeText(titleInput, postData.title);
fireEvent.changeText(contentInput, postData.content);

fireEvent.press(getByText("Tech"));
fireEvent.press(getByText("Science"));

fireEvent.press(getByText("Create Post"));

await waitFor(() => getByText("Post created successfully!"));

expect(getByText("Post created successfully!")).toBeTruthy();
});

it('handles stock search correctly', async () => {
const { getByPlaceholderText, findByText } = render(<CreatePost />);

const searchInput = getByPlaceholderText("Search stocks...");
fireEvent.changeText(searchInput, "Apple");

const stockName = await findByText("Apple (AAPL)");

expect(stockName).toBeTruthy();
});

it('displays an error when stock not found', async () => {
const { getByPlaceholderText, queryByText } = render(<CreatePost />);

const searchInput = getByPlaceholderText("Search stocks...");
fireEvent.changeText(searchInput, "NonExistentStock");

const errorMessage = await waitFor(() => queryByText("Stock not found"));

expect(errorMessage).toBeTruthy();
});

});
170 changes: 170 additions & 0 deletions mobile/__tests__/Post.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import React from 'react';
import renderer from 'react-test-renderer';
import { render, waitFor, fireEvent } from '@testing-library/react-native';
import Post from '../src/pages/Post'; // Adjust the import as necessary

jest.mock('node-fetch', () => require('jest-fetch-mock'));

describe('Post Component', () => {
it('should match snapshot', () => {
const postData = {
postId: '1',
author: 'John Doe',
userMap: {},
post: {
title: 'Test Post Title',
created_at: '2024-12-16T00:00:00Z',
tags: [{ id: 1, name: 'Test Tag' }],
content: 'This is a test post content.',
stocks: [1],
liked_by: [],
},
};

const tree = renderer.create(<Post route={{ params: postData }} />).toJSON();
expect(tree).toMatchSnapshot();
});

it('should fetch post data and update state', async () => {
const mockPost = {
title: 'Test Post Title',
created_at: '2024-12-16T00:00:00Z',
tags: [{ id: 1, name: 'Test Tag' }],
content: 'This is a test post content.',
stocks: [1],
liked_by: [],
};

fetch.mockResolvedValueOnce({
ok: true,
json: async () => mockPost,
});

const { getByText } = render(<Post postId="1" baseURL="http://example.com" />);

await waitFor(() => getByText('Test Post Title'));

expect(getByText('Test Post Title')).toBeTruthy();
});

it('should handle fetch error', async () => {
fetch.mockResolvedValueOnce({
ok: false,
});

const { queryByText } = render(<Post postId="1" baseURL="http://example.com" />);

await waitFor(() => queryByText('Loading...'));

expect(queryByText('Test Post Title')).toBeNull();
});

it('should fetch comments and update state', async () => {
const mockComments = [
{ id: 1, user_id: '2', content: 'Test comment 1' },
{ id: 2, user_id: '3', content: 'Test comment 2' },
];

fetch.mockResolvedValueOnce({
ok: true,
json: async () => mockComments,
});

const { getByText } = render(<Post postId="1" baseURL="http://example.com" />);

await waitFor(() => getByText('Test comment 1'));

expect(getByText('Test comment 1')).toBeTruthy();
expect(getByText('Test comment 2')).toBeTruthy();
});

it('should handle fetch comments error', async () => {
fetch.mockResolvedValueOnce({
ok: false,
});

const { queryByText } = render(<Post postId="1" baseURL="http://example.com" />);

await waitFor(() => queryByText('Loading...'));

expect(queryByText('Test comment 1')).toBeNull();
});

it('should post a comment and update the state', async () => {
const newComment = { post_id: '1', content: 'New comment' };
const mockResponse = { id: 3, user_id: '4', content: 'New comment' };

fetch.mockResolvedValueOnce({
ok: true,
json: async () => mockResponse,
});

const { getByText, getByPlaceholderText, getByTestId } = render(
<Post postId="1" baseURL="http://example.com" accessToken="mock-token" />
);

fireEvent.changeText(getByPlaceholderText('Write a comment...'), 'New comment');
fireEvent.press(getByTestId('submit-button'));

await waitFor(() => getByText('New comment'));

expect(getByText('New comment')).toBeTruthy();
});

it('should handle post comment error', async () => {
fetch.mockResolvedValueOnce({
ok: false,
});

const { getByPlaceholderText } = render(
<Post postId="1" baseURL="http://example.com" accessToken="mock-token" />
);

fireEvent.changeText(getByPlaceholderText('Write a comment...'), 'New comment');
fireEvent.press(getByTestId('submit-button'));

await waitFor(() => expect(Alert.alert).toHaveBeenCalledWith('Error liking the post: 400'));

expect(Alert.alert).toHaveBeenCalled();
});

it('should post a like and update the state', async () => {
fetch.mockResolvedValueOnce({
ok: true,
});

const { getByText } = render(<Post postId="1" baseURL="http://example.com" accessToken="mock-token" />);

fireEvent.press(getByText('👍 Like'));

await waitFor(() => getByText('👍 Liked'));

expect(getByText('👍 Liked')).toBeTruthy();
});

it('should handle post like error', async () => {
fetch.mockResolvedValueOnce({
ok: false,
});

const { getByText } = render(<Post postId="1" baseURL="http://example.com" accessToken="mock-token" />);

fireEvent.press(getByText('👍 Like'));

await waitFor(() => expect(Alert.alert).toHaveBeenCalledWith('Error liking the post: 400'));

expect(Alert.alert).toHaveBeenCalled();
});

it('should open and close the comment input modal', () => {
const { getByText, queryByText } = render(<Post postId="1" baseURL="http://example.com" accessToken="mock-token" />);

fireEvent.press(getByText('💬 Add Comment'));

expect(queryByText('Write a comment...')).toBeTruthy();

fireEvent.press(getByText('Cancel'));

expect(queryByText('Write a comment...')).toBeNull();
});
});
13 changes: 10 additions & 3 deletions mobile/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"test": "jest"
},
"dependencies": {
"@react-native-picker/picker": "^2.10.2",
"@react-navigation/bottom-tabs": "^6.6.1",
"@react-navigation/drawer": "^6.7.2",
"@react-navigation/native": "^6.1.18",
Expand Down

0 comments on commit 8bed908

Please sign in to comment.