Skip to content

Commit

Permalink
Merge pull request #492 from social-tw/feature/add-reputation-hooks-t…
Browse files Browse the repository at this point in the history
…ests

Feature/add reputation hooks tests
  • Loading branch information
Xiawpohr authored Sep 10, 2024
2 parents 2502ca9 + 1852acd commit cbf05b1
Show file tree
Hide file tree
Showing 9 changed files with 269 additions and 24 deletions.
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { useUserState } from '@/features/core'
import { RepUserType } from '@/types/Report'
import { useCallback, useEffect } from 'react'
import { useWaitForTransactionReport } from '@/features/reporting/hooks/useGetWaitForTransactReport/useWaitForTransactionReport'
import { useReportAdjucatorsReputation } from '@/features/reporting/hooks/useReportAdjicatorsReputation/useReportAdjucatorsReputation'
import { useReportEpochKeyRepuation } from '@/features/reporting/hooks/useReportEpochKeyReputation/useReportEpochKeyRepuation'
import { isMyEpochKey } from '@/utils/helpers/epochKey'
import { useReportAdjudicatorReputation } from '@/features/reporting/hooks/useReportAdjudicatorReputation/useReportAdjudicatorReputation'
import { useReportEpochKeyReputation } from '@/features/reporting/hooks/useReportEpochKeyReputation/useReportEpochKeyReputation'
import { isMyAdjudicateNullifier } from '@/features/reporting/utils/helpers'
import { RepUserType } from '@/types/Report'
import { isMyEpochKey } from '@/utils/helpers/epochKey'
import { useCallback, useEffect } from 'react'

export function useBackgroundReputationClaim() {
const { data: reports } = useWaitForTransactionReport()
const { mutateAsync: claimAdjucatorRepuation } =
useReportAdjucatorsReputation()
const { mutateAsync: claimEpochKeyRepuation } = useReportEpochKeyRepuation()
const { mutateAsync: claimAdjucatorReputation } =
useReportAdjudicatorReputation()
const { mutateAsync: claimEpochKeyReputation } =
useReportEpochKeyReputation()
const { userState } = useUserState()

const processReports = useCallback(async () => {
Expand All @@ -27,7 +28,7 @@ export function useBackgroundReputationClaim() {
)
) {
if (!report.reportorClaimedRep) {
await claimEpochKeyRepuation({
await claimEpochKeyReputation({
reportId: report.reportId,
reportedEpochKey: BigInt(report.reportorEpochKey),
reportedEpoch: report.reportEpoch,
Expand All @@ -42,7 +43,7 @@ export function useBackgroundReputationClaim() {
)
) {
if (!report.respondentClaimedRep) {
await claimEpochKeyRepuation({
await claimEpochKeyReputation({
reportId: report.reportId,
reportedEpochKey: BigInt(report.respondentEpochKey),
reportedEpoch: report.object.epoch,
Expand All @@ -59,10 +60,10 @@ export function useBackgroundReputationClaim() {
) && !adj.claimed,
)
) {
await claimAdjucatorRepuation(report.reportId)
await claimAdjucatorReputation(report.reportId)
}
}
}, [reports, userState, claimEpochKeyRepuation, claimAdjucatorRepuation])
}, [reports, userState, claimEpochKeyReputation, claimAdjucatorReputation])

useEffect(() => {
processReports()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { SERVER } from '@/constants/config'
import { wrapper } from '@/utils/test-helpers/wrapper'
import { renderHook, waitFor } from '@testing-library/react'
import nock from 'nock'
import { useWaitForTransactionReport } from './useWaitForTransactionReport'

jest.mock('@/features/core/hooks/useUserState/useUserState', () => ({
useUserState: () => ({
getGuaranteedUserState: () => ({
id: {
secret: '0x123',
},
genProveReputationProof: jest.fn().mockResolvedValue({
publicSignals: 'mocked_signals',
proof: 'mocked_proof',
epoch: 0,
epochKey: 'mocked_epockKey',
}),
genEpochKeyLiteProof: jest.fn().mockResolvedValue({
publicSignals: 'mocked_signals',
proof: 'mocked_proof',
epoch: 0,
epochKey: 'mocked_epockKey',
}),
}),
}),
}))

jest.mock('@/features/core/hooks/useEpoch/useEpoch', () => ({
useEpoch: () => ({
currentEpoch: 2,
}),
}))

describe('useWaitForTransactionReport', () => {
afterEach(() => {
nock.restore()
})

it('should fetch pending reports', async () => {
const reports = [
{
reportId: '1',
objectId: '1',
category: 2,
reason: '偷偷置入性廣告,不OK餒!',
reportorEpochKey: '',
respondentEpochKey: '',
adjudicatorsNullifier: [],
createdAt: '2022-01-01T00:00:00.000Z',
updatedAt: '2022-01-01T00:00:00.000Z',
},
]

const expectation = nock(SERVER)
.get(
'/api/report?status=1&publicSignals=%22mocked_signals%22&proof=%22mocked_proof%22',
)
.reply(200, reports)

const { result } = renderHook(useWaitForTransactionReport, {
wrapper,
})

await waitFor(() => expect(result.current.isSuccess).toBe(true))

expect(result.current.data).toEqual(reports)

expectation.done()
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { SERVER } from '@/constants/config'
import { wrapper } from '@/utils/test-helpers/wrapper'
import { act, renderHook } from '@testing-library/react'
import nock from 'nock'
import { useReportAdjudicatorReputation } from './useReportAdjudicatorReputation'

jest.mock('@/features/core/hooks/useWeb3Provider/useWeb3Provider', () => ({
useWeb3Provider: () => ({
getGuaranteedProvider: () => ({
waitForTransaction: jest.fn(),
}),
}),
}))

jest.mock('@/features/core/hooks/useUserState/useUserState', () => ({
useUserState: () => ({
getGuaranteedUserState: () => ({
waitForSync: jest.fn(),
latestTransitionedEpoch: jest.fn().mockResolvedValue(1),
genEpochKeyProof: jest.fn().mockResolvedValue({
publicSignals: 'mocked_signals',
proof: 'mocked_proof',
epoch: 0,
epochKey: 'mocked_epockKey',
}),
genUserStateTransitionProof: jest.fn().mockResolvedValue({
publicSignals: 'mocked_signals',
proof: 'mocked_proof',
epoch: 0,
epochKey: 'mocked_epockKey',
}),
sync: {
calcCurrentEpoch: jest.fn().mockReturnValue(2),
},
}),
}),
}))

jest.mock('@/features/core/utils/genReportNullifierProof', () => ({
genReportNullifierProof: async () => ({
publicSignals: 'mocked_signals',
proof: 'mocked_proof',
}),
}))

describe('useReportAdjudicatorReputation', () => {
afterEach(() => {
nock.restore()
})

it('should claim reputation with ReportEpochKeyProof', async () => {
const expectation = nock(SERVER)
.post('/api/transition')
.reply(200, { hash: '0xhash' })
.post('/api/reputation/claim')
.reply(200, { message: { txHash: '0xhash' } })

const { result } = renderHook(() => useReportAdjudicatorReputation(), {
wrapper: wrapper,
})

await act(async () => {
await result.current.mutateAsync('1')
})

expect(result.current.error).toBeFalsy()
expectation.done()
})
})
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { MutationKeys, QueryKeys } from '@/constants/queryKeys'
import {
useActionCount,
Expand All @@ -7,11 +6,12 @@ import {
useWeb3Provider,
} from '@/features/core'
import { genReportNullifierProof } from '@/features/core/utils/genReportNullifierProof'
import { getEpochKeyNonce } from '@/utils/helpers/getEpochKeyNonce'
import { relayClaimReputation } from '@/utils/api'
import { RepUserType } from '@/types/Report'
import { relayClaimReputation } from '@/utils/api'
import { getEpochKeyNonce } from '@/utils/helpers/getEpochKeyNonce'
import { useMutation, useQueryClient } from '@tanstack/react-query'

export function useReportAdjucatorsReputation() {
export function useReportAdjudicatorReputation() {
const { stateTransition } = useUserStateTransition()
const { getGuaranteedUserState } = useUserState()
const actionCount = useActionCount()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { SERVER } from '@/constants/config'
import { RepUserType } from '@/types/Report'
import { wrapper } from '@/utils/test-helpers/wrapper'
import { act, renderHook } from '@testing-library/react'
import nock from 'nock'
import { useReportEpochKeyReputation } from './useReportEpochKeyReputation'

jest.mock('@/features/core/hooks/useWeb3Provider/useWeb3Provider', () => ({
useWeb3Provider: () => ({
getGuaranteedProvider: () => ({
waitForTransaction: jest.fn(),
}),
}),
}))

jest.mock('@/features/core/hooks/useUserState/useUserState', () => ({
useUserState: () => ({
getGuaranteedUserState: () => ({
waitForSync: jest.fn(),
latestTransitionedEpoch: jest.fn().mockResolvedValue(1),
genEpochKeyProof: jest.fn().mockResolvedValue({
publicSignals: 'mocked_signals',
proof: 'mocked_proof',
epoch: 0,
epochKey: 'mocked_epockKey',
}),
genUserStateTransitionProof: jest.fn().mockResolvedValue({
publicSignals: 'mocked_signals',
proof: 'mocked_proof',
epoch: 0,
epochKey: 'mocked_epockKey',
}),
sync: {
calcCurrentEpoch: jest.fn().mockReturnValue(2),
},
}),
}),
}))

jest.mock('@/features/core/utils/genReportNonNullifierProof', () => ({
genReportNonNullifierProof: async () => ({
publicSignals: 'mocked_signals',
proof: 'mocked_proof',
}),
}))

describe('useReportEpochKeyReputation', () => {
afterEach(() => {
nock.restore()
})

it('should claim reputation with ReportEpochKeyProof', async () => {
const expectation = nock(SERVER)
.post('/api/transition')
.reply(200, { hash: '0xhash' })
.post('/api/reputation/claim')
.reply(200, { message: { txHash: '0xhash' } })

const { result } = renderHook(() => useReportEpochKeyReputation(), {
wrapper: wrapper,
})

await act(async () => {
await result.current.mutateAsync({
reportId: '1',
reportedEpochKey: BigInt('1'),
reportedEpoch: 1,
repUserType: RepUserType.POSTER,
})
})

expect(result.current.error).toBeFalsy()
expectation.done()
})
})
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { MutationKeys, QueryKeys } from '@/constants/queryKeys'
import {
useActionCount,
Expand All @@ -7,11 +6,12 @@ import {
useWeb3Provider,
} from '@/features/core'
import { genReportNonNullifierProof } from '@/features/core/utils/genReportNonNullifierProof'
import { getEpochKeyNonce } from '@/utils/helpers/getEpochKeyNonce'
import { relayClaimReputation } from '@/utils/api'
import { RepUserType } from '@/types/Report'
import { relayClaimReputation } from '@/utils/api'
import { getEpochKeyNonce } from '@/utils/helpers/getEpochKeyNonce'
import { useMutation, useQueryClient } from '@tanstack/react-query'

export function useReportEpochKeyRepuation() {
export function useReportEpochKeyReputation() {
const { stateTransition } = useUserStateTransition()
const { getGuaranteedUserState } = useUserState()
const actionCount = useActionCount()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { wrapper } from '@/utils/test-helpers/wrapper'
import { renderHook, waitFor } from '@testing-library/react'
import { useReputationScore } from './useReputationScore'

jest.mock('@/features/core/hooks/useUserState/useUserState', () => ({
useUserState: () => ({
userState: {
id: '1',
getData: jest.fn().mockResolvedValue([10, 5, 0, 0]),
},
}),
}))

describe('useReputationScore', () => {
it('should return the reputation score', async () => {
const { result } = renderHook(() => useReputationScore(), {
wrapper: wrapper,
})

await waitFor(() => expect(result.current.isSuccess).toBe(true))

expect(result.current.reputationScore).toEqual(5)
expect(result.current.isValidReputationScore).toBe(true)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { useQuery } from '@tanstack/react-query'

export function useReputationScore() {
const { userState } = useUserState()
const { data: reputationScore } = useQuery({

const reputationScoreQuery = useQuery({
queryKey: [QueryKeys.ReputationScore, userState?.id.toString()],
queryFn: async () => {
if (!userState) {
Expand All @@ -15,10 +16,13 @@ export function useReputationScore() {
},
})

const { data: reputationScore, ...otherProps } = reputationScoreQuery

const isValidReputationScore =
reputationScore !== undefined && reputationScore >= 0

return {
...otherProps,
reputationScore,
isValidReputationScore,
}
Expand Down
6 changes: 3 additions & 3 deletions packages/frontend/src/features/reporting/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ export { default as AdjudicationNotification } from './components/AdjudicateNoti
export { default as CheckIn } from './components/CheckIn/CheckIn'
export { default as CheckInNotification } from './components/CheckInNotification/CheckInNotification'
export { useAdjudicate } from './hooks/useAdjudicate/useAdjudicate'
export { useBackgroundReputationClaim } from './hooks/useBackgroundReputationClaim/useBackgroundReputationClaim'
export { useCheckIn } from './hooks/useCheckIn/useCheckIn'
export { useFetchReportCategories } from './hooks/useFetchReportCategories/useFetchReportCategories'
export { useNotifyCheckIn } from './hooks/useNotifyCheckIn/useNotifyCheckIn'
export { usePendingReports } from './hooks/usePendingReports/usePendingReports'
export { useReportAdjudicatorReputation } from './hooks/useReportAdjudicatorReputation/useReportAdjudicatorReputation'
export { useReportEpochKeyReputation } from './hooks/useReportEpochKeyReputation/useReportEpochKeyReputation'
export { useReputationScore } from './hooks/useReputationScore/useReputationScore'
export { useBackgroundReputationClaim } from './hooks/useBackgroundReputationClaim/useBackgroundReputationClaim'
export { useReportAdjucatorsReputation } from './hooks/useReportAdjicatorsReputation/useReportAdjucatorsReputation'
export { useReportEpochKeyRepuation } from './hooks/useReportEpochKeyReputation/useReportEpochKeyRepuation'

0 comments on commit cbf05b1

Please sign in to comment.