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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

馃┕ Address some slow or inconsistent tests #4368

Merged
merged 4 commits into from
Jun 5, 2023
Merged
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
7 changes: 2 additions & 5 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,8 @@
{
"groups": ["builtin", "external", "parent", ["index", "sibling"]],
"pathGroups": [
{
"pattern": "@/**",
"group": "external",
"position": "after"
}
{ "pattern": "@test/**", "position": "after", "group": "builtin" },
{ "pattern": "@/**", "position": "after", "group": "external" }
],
"pathGroupsExcludedImportTypes": ["builtin"],
"newlines-between": "always",
Expand Down
1 change: 1 addition & 0 deletions packages/ui/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ module.exports = {
moduleNameMapper: {
'\\.(svg|css|md)$': '<rootDir>/test/_mocks/imports/fileMock.js',
'^@/(.*)$': '<rootDir>/src/$1',
'^@test/(.*)$': '<rootDir>/test/$1',
// since jest doesn't support importing modules by `exports` in package.json
// we are forced to make mapping manually
'^@joystream/js/content': '@joystream/js/lib/mjs/content',
Expand Down
2 changes: 1 addition & 1 deletion packages/ui/src/bounty/components/BountyFooter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const BountyFooter = ({ bounty }: Props) => {
return (
<BountyInfoWrapper>
<TextSmall>
{t('created')}: {formatDateString(bounty.createdAt, 'l')}
{t('created')}: {formatDateString(bounty.createdAt)}
</TextSmall>
<Separator>{' | '}</Separator>
<BlockInfo
Expand Down
2 changes: 1 addition & 1 deletion packages/ui/src/common/components/BlockTime/BlockTime.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const BlockTime = React.memo(({ block, layout, dateLabel, lessInfo, posit
<BlockTimeWrapper layout={layout} position={position}>
<AboutText>
{dateLabel && layout == 'row' && dateLabel + ': '}
{formatDateString(block.timestamp, layout === 'column' ? 's' : 'l')}
{formatDateString(block.timestamp)}
</AboutText>
{layout == 'row' && <Separator>{' | '}</Separator>}
<BlockInfo block={block} lessInfo={lessInfo} />
Expand Down
10 changes: 2 additions & 8 deletions packages/ui/src/common/model/formatters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,12 @@ export const DefaultDateFormatter = Intl.DateTimeFormat('en-GB', {
timeZoneName: 'short',
})

export const formatDateString = (timestamp: string | number | undefined, size: 's' | 'l' = 'l') => {
export const formatDateString = (timestamp: string | number | undefined) => {
if (!isDefined(timestamp)) {
return '-'
}

const defaultFormat = DefaultDateFormatter.format(new Date(timestamp))
switch (size) {
case 'l':
return defaultFormat.replace(/ ([AP]M)/i, (_, period: string) => period.toUpperCase())
default:
return defaultFormat
}
return DefaultDateFormatter.format(new Date(timestamp)).toUpperCase()
}

type TimeUnit = [number, Intl.RelativeTimeFormatUnit]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const ThreadItemBreadcrumbs = memo(({ id, nonInteractive }: ThreadItemBre
{title}
</BreadcrumbsItem>
)),
[isLoading, nonInteractive]
[breadcrumbs, nonInteractive]
)

const containerRef = useRef<HTMLUListElement>(null)
Expand All @@ -56,7 +56,7 @@ export const ThreadItemBreadcrumbs = memo(({ id, nonInteractive }: ThreadItemBre

const { children } = containerRef.current
return [children[0], last(children)].map((child) => child.getBoundingClientRect().width)
}, [isLoading])
}, [isLoading, containerRef.current])

useEffect(() => {
if (!lastChildWidth || !firstChildWidth) return
Expand Down
Original file line number Diff line number Diff line change
@@ -1,35 +1,26 @@
import { useEffect, useMemo, useState } from 'react'

import { useGetForumCategoryBreadcrumbLazyQuery } from '../queries'
import { useGetForumCategoryBreadcrumbQuery } from '../queries'
import { asSubCategory, CategoryBreadcrumb } from '../types'

// The goal of this hook is to utilize apollo cache to be faster than `useForumCategoryBreadcrumbs`
// when there are a lot of breadcrumbs to show, like on search results
export const useForumMultiQueryCategoryBreadCrumbs = (id: string) => {
const placeholder = useMemo(() => [{ id, title: `Category ${id}` }], [id])
const [isLoading, setIsLoading] = useState(true)
const [breadcrumbs, setBreadcrumbs] = useState<CategoryBreadcrumb[]>([])
const [getCategory, { data }] = useGetForumCategoryBreadcrumbLazyQuery()

useEffect(() => {
setBreadcrumbs([])
getCategory({ variables: { where: { id } } })
}, [id])
const [nextId, setNextId] = useState(id)
const { data } = useGetForumCategoryBreadcrumbQuery({ variables: { where: { id: nextId } }, skip: !nextId })

useEffect(() => {
const category = data?.forumCategoryByUniqueInput
if (!category) return

if (category.parentId) {
getCategory({ variables: { where: { id: category.parentId } } })
} else {
setIsLoading(false)
}
setNextId(category.parentId ?? '')
setBreadcrumbs([asSubCategory(category), ...breadcrumbs])
}, [data])

return {
isLoading,
breadcrumbs: isLoading ? placeholder : breadcrumbs,
isLoading: !!nextId,
breadcrumbs: nextId ? placeholder : breadcrumbs,
}
}
7 changes: 7 additions & 0 deletions packages/ui/test/_helpers/mockUniqueQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const mockUniqueQuery = <T extends { id: string }>(key: string, entities: T[]) =>
jest.fn(({ variables, skip }) => {
if (skip) return {}
const { id } = variables.where
const entity = entities.find((entity) => entity.id === id)
return { isLoading: false, data: { [key]: entity } }
})
2 changes: 1 addition & 1 deletion packages/ui/test/common/model/formatters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ describe('formatters', () => {
const dateString = '1983-10-01T06:42:00.155Z'

it('Default format', () => {
expect(formatDateString(dateString)).toMatch(/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}, [0-9]{2}:[0-9]{2}(AM|PM) [A-Z]+/)
expect(formatDateString(dateString)).toMatch(RegExp(String.raw`\d{2}/\d{2}/\d{4}, \d{2}:\d{2}\s[AP]M [A-Z]+$`))
})
})

Expand Down
2 changes: 1 addition & 1 deletion packages/ui/test/council/modals/RestoreVotesModal.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ describe('UI: Restore Votes Modal', () => {
displayModal()
await uploadFile(createFile('not json'))
expect(await screen.findByRole('button', { name: 'Restore Votes' })).toBeDisabled()
expect(await screen.findByText(/^Unexpected token .+ in JSON/)).toBeDefined()
expect(await screen.findByText(/^Unexpected token/)).toBeDefined()
})

it('Invalid schema', async () => {
Expand Down
20 changes: 7 additions & 13 deletions packages/ui/test/forum/components/ThreadItemBreadcrumbs.test.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
import { mockUniqueQuery } from '@test/_helpers/mockUniqueQuery'
import { mockCategories } from '@test/_mocks/forum'

import { render, screen } from '@testing-library/react'
import React from 'react'
import { MemoryRouter } from 'react-router-dom'

import { ThreadItemBreadcrumbs } from '@/forum/components/threads/ThreadItemBreadcrumbs'
import { seedForumCategory } from '@/mocks/data/seedForum'

import { mockCategories } from '../../_mocks/forum'
import { MockQueryNodeProviders } from '../../_mocks/providers'
import { setupMockServer } from '../../_mocks/server'
jest.mock('@/forum/queries', () => ({
useGetForumCategoryBreadcrumbQuery: mockUniqueQuery('forumCategoryByUniqueInput', mockCategories),
}))

describe('ThreadItemBreadcrumbs', () => {
const server = setupMockServer({ noCleanupAfterEach: true })

beforeAll(() => {
mockCategories.map((category) => seedForumCategory(category, server.server))
})

it('Default', async () => {
renderComponent('4')
expect(await screen.findByText('Forum')).toBeDefined()
Expand All @@ -29,9 +25,7 @@ describe('ThreadItemBreadcrumbs', () => {
function renderComponent(id: string) {
render(
<MemoryRouter>
<MockQueryNodeProviders>
<ThreadItemBreadcrumbs id={id} />
</MockQueryNodeProviders>
<ThreadItemBreadcrumbs id={id} />
</MemoryRouter>
)
}
Expand Down
1 change: 1 addition & 0 deletions packages/ui/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@test/*": ["test/*"],
"@polkadot/api/augment": ["../types/augment/augment-api.ts"],
"@polkadot/types/augment": ["../types/augment/augment-types.ts"]
}
Expand Down