Skip to content

Commit

Permalink
Migrated tests
Browse files Browse the repository at this point in the history
  • Loading branch information
bezoerb committed Nov 11, 2021
1 parent c147a88 commit 85cb313
Show file tree
Hide file tree
Showing 27 changed files with 1,117 additions and 907 deletions.
13 changes: 12 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"lint": "eslint --color --ignore-path .gitignore",
"jest": "jest",
"test": "npm run lint && npm run jest",
"test:ci": "npm run lint && npm run jest -- --coverage",
"prebuild": "npm run clean",
"build": "tsc --build"
},
Expand Down Expand Up @@ -78,10 +79,20 @@
"ts",
"js"
],

"testRegex": "/src/.*\\.test.(js|ts)$",
"moduleDirectories": [
"node_modules"
]
],
"extensionsToTreatAsEsm": [".ts"],
"globals": {
"ts-jest": {
"useESM": true
}
},
"moduleNameMapper": {
"^(\\.{1,2}/.*)\\.js$": "$1"
}
},
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
93 changes: 93 additions & 0 deletions src/__test__/mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import type { Config, RuntimeContext, TransformContext } from '../types.js';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs-extra';
import {
FIELD_TYPE_LINK,
LINK_TYPE_ENTRY,
LINK_TYPE_ASSET,
getFieldSettings,
} from '../helper/contentful.js';
import { HookManager } from '../helper/hook-manager.js';

const cache = new Map();

export const readFixture = async (file) => {
if (!cache.has(file)) {
const content = await fs.readJSON(path.join(__dirname, 'fixtures', file));
cache.set(file, content);
}

return cache.get(file);
};

export const readFixtureSync = (file) => {
if (!cache.has(file)) {
const content = fs.readJSONSync(path.join(__dirname, 'fixtures', file));
cache.set(file, content);
}

return cache.get(file);
};

export const getContent = async () => {
const assets = await readFixture('assets.json');
const entries = await readFixture('entries.json');
const locales = await readFixture('locales.json');
const contentTypes = await readFixture('content_types.json');

const [entry] = entries;
const [asset] = assets;
const assetLink = {
sys: {
id: 'asset-id',
type: FIELD_TYPE_LINK,
linkType: LINK_TYPE_ASSET,
},
};

const entryLink = {
sys: {
id: 'entry-id',
type: FIELD_TYPE_LINK,
linkType: LINK_TYPE_ENTRY,
},
};

return { entries, assets, contentTypes, locales, assetLink, entryLink, entry, asset };
};

export const getConfig = (fixture: Partial<Config> = {}): Config => {
return {
...fixture,
} as Config;
};
export const getRuntimeContext = (fixture: Partial<RuntimeContext> = {}): RuntimeContext => {
const assets = readFixtureSync('assets.json');
const entries = readFixtureSync('entries.json');
const locales = readFixtureSync('locales.json');
const contentTypes = readFixtureSync('content_types.json');

const fieldSettings = getFieldSettings(contentTypes);
const { code: defauleLocale } = locales.find((locale) => locale.default) || locales[0];

const result = {
config: getConfig(),
localized: new Map(),
data: {
assets,
entries,
contentTypes,
locales,
fieldSettings,
},
defauleLocale,
...fixture,
};

const hooks = new HookManager(result as RuntimeContext, getConfig());

return { ...result, hooks } as RuntimeContext;
};
export const getTransformContext = (fixture: Partial<TransformContext> = {}): TransformContext =>
({ assets:[], entries:[], assetMap: new Map(), entryMap: new Map(), ...fixture } as TransformContext);
10 changes: 5 additions & 5 deletions test/converter.test.js → src/converter/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { parse, stringify, JSON, MARKDOWN, YAML, TOML } = require('../lib/converter');
import { parse, stringify, TYPE_JSON, TYPE_MARKDOWN, TYPE_YAML, TYPE_TOML } from './index.js';

const src = {
languages: {
Expand All @@ -17,22 +17,22 @@ const src = {

describe('Converter', () => {
test('parse & stringify json', () => {
const obj = parse(stringify(src, JSON), JSON);
const obj = parse(stringify(src, TYPE_JSON), TYPE_JSON);
expect(obj).toMatchObject(src);
});

test('parse & stringify yaml', () => {
const obj = parse(stringify(src, YAML), YAML);
const obj = parse(stringify(src, TYPE_YAML), TYPE_YAML);
expect(obj).toMatchObject(src);
});

test('parse & stringify toml', () => {
const obj = parse(stringify(src, TOML), TOML);
const obj = parse(stringify(src, TYPE_TOML), TYPE_TOML);
expect(obj).toMatchObject(src);
});

test('parse & stringify markdown', () => {
const obj = parse(stringify(src, MARKDOWN), MARKDOWN);
const obj = parse(stringify(src, TYPE_MARKDOWN), TYPE_MARKDOWN);
expect(obj).toMatchObject(src);
});
});
2 changes: 1 addition & 1 deletion test/json.test.js → src/converter/json.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { stringify, parse } = require('../lib/converter/json');
import { stringify, parse } from './json.js';

describe('JSON', () => {
test('parse & stringify', () => {
Expand Down
2 changes: 1 addition & 1 deletion test/markdown.test.js → src/converter/markdown.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { stringify, parse } = require('../lib/converter/markdown');
import { stringify, parse } from './markdown.js';

describe('Markdown', () => {
test('Markdown frontmatter', () => {
Expand Down
2 changes: 1 addition & 1 deletion test/toml.test.js → src/converter/toml.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { stringify, parse } = require('../lib/converter/toml');
import { stringify, parse } from './toml.js';

describe('TOML', () => {
test('grow schema', () => {
Expand Down
2 changes: 1 addition & 1 deletion test/yaml.test.js → src/converter/yaml.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { stringify, parse } = require('../lib/converter/yaml');
import { stringify, parse } from './yaml.js';

describe('YAML', () => {
test('grow schema', () => {
Expand Down
12 changes: 4 additions & 8 deletions src/helper/config.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
/* eslint-disable complexity */
import type {ContentfulConfig, PluginInfo, Hooks, Config, InitialConfig, KeyValueMap} from '../types.js';

import {isAbsolute, resolve, dirname} from 'path';
// import load, {Config as ProloadConfig} from '@proload/core';
// import json from '@proload/plugin-json';
// import rc from '@proload/plugin-rc';
// import typescript from '@proload/plugin-typescript';
import { createRequire } from 'module';
import {isAbsolute, resolve} from 'path';
import {cosmiconfig} from 'cosmiconfig';
import TypeScriptLoader from '@endemolshinegroup/cosmiconfig-typescript-loader';
import mergeOptionsModule from 'merge-options';
import {removeEmpty} from './object.js';

// const require = createRequire(process.cwd());
//

// load.use([json, typescript, rc]);

Expand All @@ -21,7 +17,7 @@ const mergeOptions = mergeOptionsModule.bind({ignoreUndefined: true});
const resolvePlugin = async (plugin: string | PluginInfo): Promise<Hooks> => {
const pluginName = typeof plugin === 'string' ? plugin : plugin.resolve;
const pluginOptions = typeof plugin === 'string' ? {} : plugin.options || {};

const require = createRequire(import.meta.url);
const resolvedPath = require.resolve(pluginName);

const module = await import(resolvedPath) as Hooks | ((...args: unknown[]) => Hooks);
Expand Down
29 changes: 13 additions & 16 deletions test/contentful.test.js → src/helper/contentful.test.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,17 @@
const { TestScheduler } = require('jest');
/* eslint-env jest */
const { getContent } = require('./utils');
const {
getClient,
getSpaces,
getSpace,
getEnvironments,
getEnvironment,
import { getContent } from '../__test__/mock.js';
import {
convertToMap,
getContentId,
getContentTypeId,
getEnvironmentId,
isAssetLink,
isEntryLink,
getFieldSettings,
isAsset,
isAssetLink,
isEntry,
isEntryLink,
isLink,
getFieldSettings,
getApiKey,
getPreviewApiKey,
convertToMap,
} = require('../lib/contentful');
} from './contentful';

describe('Contentful', () => {
test('isAssetLink', async () => {
Expand Down Expand Up @@ -101,7 +93,12 @@ describe('Contentful', () => {
const { entries } = await getContent();
const entryMap = convertToMap(entries);

const ids = ['34O95Y8gLXd3jPozdy7gmd', 'WLITBNhFp0VzHqOwKJAwR', '56O29iIIcee0ZcgIuwlHSv', '2WLqjLlMJUbc0vCf9UMfjA'];
const ids = [
'34O95Y8gLXd3jPozdy7gmd',
'WLITBNhFp0VzHqOwKJAwR',
'56O29iIIcee0ZcgIuwlHSv',
'2WLqjLlMJUbc0vCf9UMfjA',
];

expect(entryMap.size).toBe(ids.length);
ids.forEach((id) => expect(entryMap.has(id)).toBe(true));
Expand Down
7 changes: 2 additions & 5 deletions src/helper/contentful.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@ import type {ContentfulConfig, FieldSettings, Node, Entry, Asset, ContentType, L
import contentful from 'contentful';
import contentfulManagement from 'contentful-management';

const {createClient: createManagementClient} = contentfulManagement;
const {createClient} = contentful;

let client: ContentfulClientApi;
let managementClient: ContentfulManagementApi;

Expand Down Expand Up @@ -68,7 +65,7 @@ const getClient = (options: ContentfulConfig): ContentfulClientApi => {
accessToken: preview ? previewAccessToken : accessToken,
environment: environmentId,
};
return createClient(params);
return contentful.createClient(params);
}

throw new Error('You need to login first. Run npx contentful login');
Expand All @@ -86,7 +83,7 @@ const getManagementClient = (options: ContentfulConfig): ContentfulManagementApi
}

if (managementToken) {
return createManagementClient({
return contentfulManagement.createClient({
accessToken: managementToken,
});
}
Expand Down
1 change: 1 addition & 0 deletions src/helper/object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ test('groupBy', () => {
});
});


test('snakeCaseKeys', () => {
const value = {aTest: [{testOne: 1, t: 2}], A: 'b'};
const expected = {a_test: [{test_one: 1, t: 2}], a: 'b'};
Expand Down
30 changes: 30 additions & 0 deletions src/helper/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Entry } from '../types.js';
import { collect } from './utils.js';

test('collect', () => {
const data = [
{ sys: { id: 1 }, fields: { slug: 'a' } },
{ sys: { id: 2 }, fields: { slug: 'b', parent: 1 } },
{ sys: { id: 3 }, fields: { slug: 'c', parent: 2 } },
{ sys: { id: 4 }, fields: { slug: 'd', parent: 3 } },
{ sys: { id: 5 }, fields: { slug: 'e', parent: 4 } },
];

const getter = {
getId: (item) => item.sys.id,
getNextId: (item) => item.fields.parent,
getValue: (item) => item.fields.slug,
};

const a = collect(data[4] as unknown as Entry, data as unknown as Entry[], {
...getter,
reverse: true,
});
const b = collect(data[4] as unknown as Entry, data as unknown as Entry[], {
...getter,
reverse: false,
});

expect(a).toEqual(['a', 'b', 'c', 'd', 'e']);
expect(b).toEqual(['e', 'd', 'c', 'b', 'a']);
});
34 changes: 19 additions & 15 deletions test/localize.test.js → src/tasks/localize.test.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,28 @@
/* eslint-env jest */
const { getContent } = require('./utils');
const { getContentId, getFieldSettings } = require('../lib/contentful');
import type { Locale } from '../types.js';
import { getContent } from '../__test__/mock.js';
import { getContentId, getFieldSettings } from '../helper/contentful.js';

const { localizeEntry, localizeField, getLocaleList } = require('../lib/transform/localize');
import { localizeEntry, localizeField, getLocaleList } from './localize.js';

const getLocale = (code, fallback):Locale => ({
name: `Locale: ${code}`,
code: `${code}`,
fallbackCode: `${fallback}`,
default: false,
sys: {
id: `locale-${code}`,
type: 'Locale',
version: 1
}
})

describe('Localize', () => {
test('getLocaleList', async () => {
const locales = [
{
code: '1',
fallbackCode: '2',
},
{
code: '2',
fallbackCode: '3',
},
{
code: '3',
fallbackCode: '4',
},
getLocale(1,2),
getLocale(2,3),
getLocale(3,4),
];

expect(getLocaleList('1', locales).join('-')).toEqual('1-2-3');
Expand Down
6 changes: 3 additions & 3 deletions src/tasks/localize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {convertToMap, getContentTypeId} from '../helper/contentful.js';
* @param {Array} locales Array of contentful locale objects
* @returns {Array} E.g. ['en-US', 'en-GB', 'de-DE']
*/
const getLocaleList = (code: string | null, locales: Locale[] = []): string[] => {
export const getLocaleList = (code: string | null, locales: Locale[] = []): string[] => {
const locale = locales.find(locale => locale.code === code);
return locale ? [locale.code, ...getLocaleList(locale.fallbackCode, locales)] : [];
};
Expand All @@ -19,7 +19,7 @@ const getLocaleList = (code: string | null, locales: Locale[] = []): string[] =>
* @param {Object} field Object with values for different locales { 'de-DE': '...', 'en-US': '...' }
* @param {...any} codes Array with codes generated by getLocaleList
*/
const localizeField = <T extends Record<string, any>>(field: T, ...codes: string[]): any => {
export const localizeField = <T extends Record<string, any>>(field: T, ...codes: string[]): any => {
const [code, ...fallbackCodes] = codes;
if (code && Object.prototype.hasOwnProperty.call(field, code)) {
return field[code];
Expand All @@ -36,7 +36,7 @@ const localizeField = <T extends Record<string, any>>(field: T, ...codes: string
* @param {String} code Locale code e.g. 'de-DE'
* @param {Object} data Object containing locales & content types from contentful
*/
const localizeEntry = <T extends Node>(node: T, code: string, data: Partial<ContentfulData>): T => {
export const localizeEntry = <T extends Node>(node: T, code: string, data: Partial<ContentfulData>): T => {
const {locales, fieldSettings} = data;

const {fields} = node;
Expand Down
Loading

0 comments on commit 85cb313

Please sign in to comment.