Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create API for research search #3987

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
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
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,7 @@ const ResearchFieldCategory = () => {
useEffect(() => {
const getCategories = async () => {
const categories = await researchService.getResearchCategories()
setOptions(
categories
.filter((x) => !x._deleted)
.map((x) => ({ label: x.label, value: x })),
)
setOptions(categories.map((x) => ({ label: x.label, value: x })))
}

getCategories()
Expand Down
20 changes: 7 additions & 13 deletions src/pages/Research/Content/ResearchList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,13 @@ import DraftButton from 'src/pages/common/Drafts/DraftButton'
import useDrafts from 'src/pages/common/Drafts/useDrafts'
import { Box, Flex, Heading, useThemeUI } from 'theme-ui'

import { ITEMS_PER_PAGE, RESEARCH_EDITOR_ROLES } from '../constants'
import { RESEARCH_EDITOR_ROLES } from '../constants'
import { listing } from '../labels'
import { researchService } from '../research.service'
import { ResearchFilterHeader } from './ResearchFilterHeader'
import ResearchListItem from './ResearchListItem'
import { ResearchSearchParams } from './ResearchSearchParams'

import type { DocumentData, QueryDocumentSnapshot } from 'firebase/firestore'
import type { IResearch, ResearchStatus } from 'oa-shared'
import type { ThemeWithName } from 'oa-themes'
import type { ResearchSortOption } from '../ResearchSortOptions'
Expand All @@ -34,9 +33,7 @@ const ResearchList = observer(() => {
getDrafts: researchService.getDrafts,
})
const [total, setTotal] = useState<number>(0)
const [lastVisible, setLastVisible] = useState<
QueryDocumentSnapshot<DocumentData, DocumentData> | undefined
>(undefined)
const [lastId, setLastId] = useState<string | undefined>(undefined)

const [searchParams, setSearchParams] = useSearchParams()
const q = searchParams.get(ResearchSearchParams.q) || ''
Expand All @@ -63,9 +60,7 @@ const ResearchList = observer(() => {
}
}, [q, category, status, sort])

const fetchResearchItems = async (
skipFrom?: QueryDocumentSnapshot<DocumentData, DocumentData>,
) => {
const fetchResearchItems = async (lastDocId?: string) => {
setIsFetching(true)

try {
Expand All @@ -76,18 +71,17 @@ const ResearchList = observer(() => {
category,
sort,
status,
skipFrom,
ITEMS_PER_PAGE,
lastDocId,
)

if (skipFrom) {
if (lastDocId) {
// if skipFrom is set, means we are requesting another page that should be appended
setResearchItems((items) => [...items, ...result.items])
} else {
setResearchItems(result.items)
}

setLastVisible(result.lastVisible)
setLastId(result.items[result.items.length - 1]._id)

setTotal(result.total)
} catch (error) {
Expand Down Expand Up @@ -187,7 +181,7 @@ const ResearchList = observer(() => {
>
<Button
type="button"
onClick={() => fetchResearchItems(lastVisible)}
onClick={() => fetchResearchItems(lastId)}
>
{listing.loadMore}
</Button>
Expand Down
197 changes: 93 additions & 104 deletions src/pages/Research/research.service.test.ts
Original file line number Diff line number Diff line change
@@ -1,120 +1,109 @@
import '@testing-library/jest-dom/vitest'

import { ResearchStatus } from 'oa-shared'
import { describe, expect, it, vi } from 'vitest'

import { exportedForTesting } from './research.service'

const mockWhere = vi.fn()
const mockOrderBy = vi.fn()
const mockLimit = vi.fn()
vi.mock('firebase/firestore', () => ({
collection: vi.fn(),
query: vi.fn(),
and: vi.fn(),
where: (path, op, value) => mockWhere(path, op, value),
limit: (limit) => mockLimit(limit),
orderBy: (field, direction) => mockOrderBy(field, direction),
}))

vi.mock('../../stores/databaseV2/endpoints', () => ({
DB_ENDPOINTS: {
research: 'research',
researchCategories: 'researchCategories',
},
}))

vi.mock('../../config/config', () => ({
getConfigurationOption: vi.fn(),
FIREBASE_CONFIG: {
apiKey: 'AIyChVN',
databaseURL: 'https://test.firebaseio.com',
projectId: 'test',
storageBucket: 'test.appspot.com',
},
localStorage: vi.fn(),
SITE: 'unit-tests',
}))

describe('research.search', () => {
it('searches for text', () => {
// prepare
const words = ['test', 'text']

// act
exportedForTesting.createSearchQuery(words, '', 'MostRelevant', null)

// assert
expect(mockWhere).toHaveBeenCalledWith(
'keywords',
'array-contains-any',
words,
)
import { researchService } from './research.service'

describe('research.service', () => {
describe('search', () => {
it('fetches research articles based on search criteria', async () => {
// Mock successful fetch response
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these tests aren't very useful now, because it's just mocking and checking the mocked value, so not testing anything real.
we should instead add cypress and/or UI tests.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Im on it :)

global.fetch = vi.fn().mockResolvedValue({
json: () =>
Promise.resolve({
items: [{ id: '1', title: 'Sample Research' }],
total: 1,
}),
})

// Call search with mock parameters
const result = await researchService.search(
['sample'],
'science',
'Newest',
null,
)

// Assert results
expect(result).toEqual({
items: [{ id: '1', title: 'Sample Research' }],
total: 1,
})
})

it('handles errors in search', async () => {
global.fetch = vi.fn().mockRejectedValue('error')

const result = await researchService.search(
['sample'],
'science',
'Newest',
null,
)

expect(result).toEqual({ items: [], total: 0 })
})
})

it('filters by category', () => {
// prepare
const category = 'cat1'
describe('getResearchCategories', () => {
it('fetches research categories', async () => {
global.fetch = vi.fn().mockResolvedValue({
json: () =>
Promise.resolve({ categories: [{ id: 'cat1', name: 'Science' }] }),
})

// act
exportedForTesting.createSearchQuery([], category, 'MostRelevant', null)
const result = await researchService.getResearchCategories()

// assert
expect(mockWhere).toHaveBeenCalledWith(
'researchCategory._id',
'==',
category,
)
})
expect(result).toEqual([{ id: 'cat1', name: 'Science' }])
})

it('handles errors in fetching research categories', async () => {
global.fetch = vi.fn().mockRejectedValue('error')

it('should not call orderBy if sorting by most relevant', () => {
// act
exportedForTesting.createSearchQuery(['test'], '', 'MostRelevant', null)
const result = await researchService.getResearchCategories()

// assert
expect(mockOrderBy).toHaveBeenCalledTimes(0)
expect(result).toEqual([])
})
})

it('should call orderBy when sorting is not MostRelevant', () => {
// act
exportedForTesting.createSearchQuery(['test'], '', 'Newest', null)
describe('getDraftCount', () => {
it('fetches draft count for a user', async () => {
global.fetch = vi.fn().mockResolvedValue({
json: () => Promise.resolve({ total: 5 }),
})

// assert
expect(mockOrderBy).toHaveBeenLastCalledWith('_created', 'desc')
})
const result = await researchService.getDraftCount('user123')

expect(result).toBe(5)
})

it('handles errors in fetching draft count', async () => {
global.fetch = vi.fn().mockRejectedValue('error')

it('should filter by research status', () => {
// act
exportedForTesting.createSearchQuery(
['test'],
'',
'Newest',
ResearchStatus.COMPLETED,
)

// assert
expect(mockWhere).toHaveBeenCalledWith(
'researchStatus',
'==',
ResearchStatus.COMPLETED,
)
const result = await researchService.getDraftCount('user123')

expect(result).toBe(0)
})
})

it('should limit results', () => {
// prepare
const take = 12

// act
exportedForTesting.createSearchQuery(
['test'],
'',
'Newest',
null,
undefined,
take,
)

// assert
expect(mockLimit).toHaveBeenLastCalledWith(take)
describe('getDrafts', () => {
it('fetches research drafts for a user', async () => {
global.fetch = vi.fn().mockResolvedValue({
json: () =>
Promise.resolve({
items: [{ id: 'draft1', title: 'Draft Research' }],
}),
})

const result = await researchService.getDrafts('user123')

expect(result).toEqual([{ id: 'draft1', title: 'Draft Research' }])
})

it('handles errors in fetching drafts', async () => {
global.fetch = vi.fn().mockRejectedValue('error')

const result = await researchService.getDrafts('user123')

expect(result).toEqual([])
})
})
})
Loading
Loading