Skip to content

Commit

Permalink
Merge pull request #39 from Q42/maintenance/unit-tests
Browse files Browse the repository at this point in the history
Unit tests
  • Loading branch information
djohalo2 authored Jul 17, 2024
2 parents 42ef3cd + 1aaf9b5 commit cb08235
Show file tree
Hide file tree
Showing 7 changed files with 1,525 additions and 267 deletions.
1,561 changes: 1,304 additions & 257 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@
"scripts": {
"build": "run-s clean && plugin-kit verify-package --silent && pkg-utils build --strict && pkg-utils --strict",
"clean": "rimraf dist",
"test": "TZ=UTC vitest run",
"test:watch": "TZ=UTC vitest",
"format": "prettier --write --cache --ignore-unknown .",
"link-watch": "plugin-kit link-watch",
"lint": "eslint ./src/** --ext=.ts,.tsx --max-warnings 0",
Expand All @@ -94,6 +96,7 @@
"@types/styled-components": "^5.1.28",
"@typescript-eslint/eslint-plugin": "^6.13.2",
"@typescript-eslint/parser": "^6.13.2",
"@vitejs/plugin-react": "^4.3.1",
"eslint": "^8.55.0",
"eslint-config-prettier": "^9.1.0",
"eslint-config-sanity": "^7.0.1",
Expand All @@ -108,7 +111,8 @@
"react-is": "^18.2.0",
"rimraf": "^5.0.5",
"sanity": "^3.21.1",
"typescript": "^5.3.3"
"typescript": "^5.3.3",
"vitest": "^2.0.2"
},
"peerDependencies": {
"react": "^18",
Expand Down
2 changes: 1 addition & 1 deletion src/components/PageTreeViewItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export const PageTreeViewItem = ({
onClick={onItemClick}>
<Flex align="center" gap={3}>
<UrlText isDisabled={isDisabled} textOverflow="ellipsis">
{parentPath ? page.slug?.current : getRootPageSlug(page, config)}
{parentPath ? page.slug?.current : getRootPageSlug(page, config) ?? '/'}
</UrlText>
{!isDisabled && (isHovered || hasActionOpen) && (
<PageTreeViewItemActions
Expand Down
4 changes: 2 additions & 2 deletions src/helpers/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ export const getLanguageFieldName = (config: PageTreeConfig) =>
config.documentInternationalization?.languageFieldName ?? 'language';

export const getRootPageSlug = (page: RawPageMetadata, config: PageTreeConfig) => {
if (!config.documentInternationalization) return '/';
if (!config.documentInternationalization) return;

const language = page[getLanguageFieldName(config)];
if (typeof language != 'string') {
throw new Error(`Language field is not a string: ${language}`);
}
return `${language}`;
return language;
};
190 changes: 190 additions & 0 deletions src/helpers/page-tree.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
import { describe, expect, it } from 'vitest';

import { NestedPageTreeItem, PageTreeConfig, RawPageMetadata } from '../types';
import { findPageTreeItemById, flatMapPageTree, getAllPageMetadata, mapRawPageMetadatasToPageTree } from './page-tree';

const config: PageTreeConfig = {
apiVersion: '2023-01-01',
rootSchemaType: 'homePage',
pageSchemaTypes: ['homePage', 'contentPage'],
titleFieldName: 'title',
baseUrl: 'https://example.com',
documentInternationalization: {
supportedLanguages: ['en', 'nl'],
},
};

const rawHomePage: RawPageMetadata = {
_id: 'home',
_type: 'homePage',
_updatedAt: '2023-01-01T00:00:00Z',
language: 'en',
};

const rawParentContentPage: RawPageMetadata = {
_id: 'parent',
_type: 'contentPage',
_updatedAt: '2023-01-01T00:00:00Z',
parent: { _ref: 'home', _type: 'reference' },
slug: { current: 'parent' },
language: 'en',
};

const rawChildContentPage: RawPageMetadata = {
_id: 'child',
_type: 'contentPage',
_updatedAt: '2023-01-01T00:00:00Z',
parent: { _ref: 'parent', _type: 'reference' },
slug: { current: 'child' },
language: 'en',
};

const rawPages: RawPageMetadata[] = [rawHomePage, rawParentContentPage, rawChildContentPage];

const pageTree: NestedPageTreeItem[] = [
{
...rawHomePage,
isDraft: false,
isPublished: true,
path: '/en',
children: [
{
...rawParentContentPage,
isDraft: false,
isPublished: true,
path: '/en/parent',
children: [
{
...rawChildContentPage,
isDraft: false,
isPublished: true,
path: '/en/parent/child',
children: [],
},
],
},
],
},
];

describe('Page tree helpers', () => {
describe('getAllPageMetadata', () => {
it('should return all page metadata from a page tree', () => {
expect(getAllPageMetadata(config, rawPages)).toStrictEqual([
{
_id: rawHomePage._id,
_updatedAt: rawHomePage._updatedAt,
type: rawHomePage._type,
path: '/en',
},
{
_id: rawParentContentPage._id,
_updatedAt: rawParentContentPage._updatedAt,
type: rawParentContentPage._type,
path: '/en/parent',
},
{
_id: rawChildContentPage._id,
_updatedAt: rawChildContentPage._updatedAt,
type: rawChildContentPage._type,
path: '/en/parent/child',
},
]);
});
});

describe('mapRawPageMetadatasToPageTree', () => {
it('should map an array raw page metadata to a nested page tree correctly', () => {
expect(mapRawPageMetadatasToPageTree(config, rawPages)).toStrictEqual(pageTree);
});

it('should omit invalid pages from page tree', () => {
expect(
mapRawPageMetadatasToPageTree(config, [
{
_id: 'missing-parent',
_type: 'contentPage',
_updatedAt: '2023-01-01T00:00:00Z',
language: 'en',
slug: { current: 'slug' },
},
{
_id: 'missing-slug',
_type: 'contentPage',
_updatedAt: '2023-01-01T00:00:00Z',
language: 'en',
parent: { _ref: 'home', _type: 'reference' },
},
]),
).toStrictEqual([]);
});

it('should omit published pages that have a draft version', () => {
expect(
mapRawPageMetadatasToPageTree(config, [
{
_id: 'home',
_type: 'homePage',
_updatedAt: '2023-01-01T00:00:00Z',
language: 'en',
},
{
_id: 'drafts.home',
_type: 'homePage',
_updatedAt: '2023-01-01T00:00:00Z',
language: 'en',
},
]),
).toStrictEqual([
{
...rawHomePage,
isDraft: true,
isPublished: true,
path: '/en',
children: [],
},
]);
});
});

describe('flatMapPageTree', () => {
it('should flatten a nested page tree correctly', () => {
expect(flatMapPageTree(pageTree)).toStrictEqual([
{
...rawHomePage,
isDraft: false,
isPublished: true,
path: '/en',
},
{
...rawParentContentPage,
isDraft: false,
isPublished: true,
path: '/en/parent',
},
{
...rawChildContentPage,
isDraft: false,
isPublished: true,
path: '/en/parent/child',
},
]);
});
});

describe('findPageTreeItemById', () => {
it('should find a page from a page tree by the given page id', () => {
expect(findPageTreeItemById(pageTree, 'child')).toStrictEqual({
...rawChildContentPage,
isDraft: false,
isPublished: true,
path: '/en/parent/child',
children: [],
});
});

it('should return undefined if the page id is not found', () => {
expect(findPageTreeItemById(pageTree, 'missing')).toBeUndefined();
});
});
});
12 changes: 6 additions & 6 deletions src/helpers/page-tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export const DRAFTS_PREFIX = 'drafts.';
/**
* Maps array of raw page metadata objects to page metadata object array containing resolved id, path and type.
*/
export const getAllPageMetadata = (config: PageTreeConfig, pagesInfo: RawPageMetadata[]): PageMetadata[] => {
const pageTree = mapRawPageMetadatasToPageTree(config, pagesInfo);
export const getAllPageMetadata = (config: PageTreeConfig, pages: RawPageMetadata[]): PageMetadata[] => {
const pageTree = mapRawPageMetadatasToPageTree(config, pages);
const flatPageTree = flatMapPageTree(pageTree);

return flatPageTree.map(page => ({
Expand Down Expand Up @@ -49,7 +49,7 @@ export const mapRawPageMetadatasToPageTree = (
config: PageTreeConfig,
pages: RawPageMetadata[],
): NestedPageTreeItem[] => {
const pagesWithPublishedState = getPublishedAndDraftRawPageMetdadata(config, pages);
const pagesWithPublishedState = getPublishedAndDraftRawPageMetadata(config, pages);

const orderedPages = orderBy(mapPageTreeItems(config, pagesWithPublishedState), 'path');
const { documentInternationalization } = config;
Expand Down Expand Up @@ -90,7 +90,7 @@ const mapPageTreeItems = (
return getChildPages(parentId).map(page => {
const pagePath = parentPath
? `${parentPath === '/' ? '' : parentPath}/${page.slug?.current}`
: getRootPageSlug(page, config);
: `/${getRootPageSlug(page, config) ?? ''}`;
const children = orderBy(mapPageTreeItems(config, pagesWithPublishedState, page._id, pagePath), 'path');

return {
Expand All @@ -104,7 +104,7 @@ const mapPageTreeItems = (
/**
* Provides draft and published status. Filters out duplicate pages with the same id and invalid pages.
*/
const getPublishedAndDraftRawPageMetdadata = (
const getPublishedAndDraftRawPageMetadata = (
config: PageTreeConfig,
pages: RawPageMetadata[],
): RawPageMetadataWithPublishedState[] => {
Expand Down Expand Up @@ -134,7 +134,7 @@ const getPublishedAndDraftRawPageMetdadata = (
};

const isValidPage = (config: PageTreeConfig, page: RawPageMetadata): boolean => {
if (page.parent === null || page.slug === null) {
if (!page.parent || !page.slug) {
if (page._type !== config.rootSchemaType) {
return false;
}
Expand Down
17 changes: 17 additions & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import react from '@vitejs/plugin-react';
import path from 'path';
import { defineConfig, UserConfig } from 'vitest/config';

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()] as UserConfig['plugins'],
test: {
include: ['src/**/*.test.ts'],
environment: 'jsdom',
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
});

0 comments on commit cb08235

Please sign in to comment.