Skip to content

Commit

Permalink
update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
kilbot committed Jul 2, 2024
1 parent 1cf924e commit 2b64ae0
Show file tree
Hide file tree
Showing 12 changed files with 979 additions and 79 deletions.
894 changes: 894 additions & 0 deletions .yarn/releases/yarn-4.3.1.cjs

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions .yarnrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
nodeLinker: node-modules

yarnPath: .yarn/releases/yarn-4.3.1.cjs
6 changes: 5 additions & 1 deletion babel.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
module.exports = function (api) {
api.cache(true);
return {
presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],
presets: [
'@babel/preset-env',
'@babel/preset-typescript',
'@babel/preset-react',
],
};
};
41 changes: 22 additions & 19 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
const TEST_REGEX = '(/__tests__/.*|(\\.|/)(test|spec))\\.(tsx?|ts?)$';

module.exports = {
roots: ['<rootDir>/tests'],
displayName: '@wcpos/query',
preset: 'ts-jest',
transform: {
'^.+\\.(ts|tsx)$': [
'ts-jest',
{
tsconfig: 'tsconfig.json',
useESM: true,
},
],
},
testRegex: TEST_REGEX,
moduleFileExtensions: ['js', 'ts', 'tsx', 'json', 'node'],
collectCoverage: true,
coveragePathIgnorePatterns: ['(tests/.*.mock).(tsx?|ts?)$'],
verbose: true,
transformIgnorePatterns: ['node_modules/(?!(@shelf/fast-natural-order-by)/)'],
testEnvironment: 'jsdom',
roots: ['<rootDir>/tests'],
displayName: '@wcpos/query',
preset: 'ts-jest',
// setupFiles: ['<rootDir>/jest.setup.js'],
transform: {
'^.+\\.(ts|tsx)$': ['ts-jest', {
tsconfig: 'tsconfig.json',
// useESM: true,
isolatedModules: true,
}],
'^.+\\.(js|jsx)$': 'babel-jest',
},
testRegex: TEST_REGEX,
moduleFileExtensions: ['ts', 'tsx', 'json', 'node', 'js', 'jsx'],
collectCoverage: true,
coveragePathIgnorePatterns: ['(tests/.*.mock).(tsx?|ts?)$'],
verbose: true,
transformIgnorePatterns: ['node_modules/(?!(lodash-es)/)'],
testEnvironment: 'jsdom',
moduleNameMapper: {
'^@wcpos/utils/src/logger$': '<rootDir>/tests/__mocks__/logger.ts',
},
};
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,19 @@
],
"scripts": {
"clean": "shx rm -rf dist && rm -rf node_modules",
"test": "jest",
"clear-jest": "jest --clearCache"
"test": "node --experimental-vm-modules ./node_modules/.bin/jest"
},
"eslintConfig": {
"extends": "@wcpos/eslint-config"
},
"packageManager": "yarn@3.5.0",
"packageManager": "yarn@4.3.1",
"dependencies": {
"@orama/orama": "^2.0.21",
"@shelf/fast-natural-order-by": "^2.0.0",
"@wcpos/components": "*",
"lodash": "^4.17.21",
"natural-orderby": "^3.0.2",
"observable-hooks": "^4.2.3",
"rxdb": "15.24.0",
"rxjs": "^7.8.1",
"typescript": "^5.4.5"
},
Expand Down
3 changes: 1 addition & 2 deletions src/query-state.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { orderBy } from '@shelf/fast-natural-order-by';
import { orderBy } from 'natural-orderby';
import cloneDeep from 'lodash/cloneDeep';
import debounce from 'lodash/debounce';
import forEach from 'lodash/forEach';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import isEqual from 'lodash/isEqual';
import { ObservableResource } from 'observable-hooks';
import { doc } from 'prettier';
import {
BehaviorSubject,
Observable,
Expand Down
4 changes: 2 additions & 2 deletions src/search-dbs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ const SPLITTERS: Record<string, RegExp> = {
chinese: /[^a-zA-Z0-9\u4e00-\u9fff]+/gim,
};

function getTokenizer(locale) {
function getTokenizer(locale = '') {
const langCode = locale.split('_')[0];
const lang = localeToLangMap[langCode] || 'english';
const splitRule = SPLITTERS[lang];
Expand Down Expand Up @@ -97,7 +97,7 @@ const searchDBs: Map<string, any> = new Map();
/**
*
*/
export async function maybeCreateSearchDB(collection, locale) {
export async function maybeCreateSearchDB(collection, locale = '') {
const langCode = locale.split('_')[0];
const language = localeToLangMap[langCode] || 'english';
const key = collection.name + '-' + language;
Expand Down
6 changes: 6 additions & 0 deletions tests/__mocks__/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
error: jest.fn(),
warn: jest.fn(),
info: jest.fn(),
debug: jest.fn(),
};
45 changes: 15 additions & 30 deletions tests/collection-replication-state.test.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,31 @@
import httpClientMock from './__mocks__/http';
import { MockRxCollection } from './__mocks__/rxdb';
import { CollectionReplicationState } from '../src/collection-replication-state';
import { createStoreDatabase, createSyncDatabase } from './helpers/db';

import type { RxCollection } from 'rxdb';
import type { RxDatabase } from 'rxdb';

describe('CollectionReplicationState', () => {
beforeEach(() => {});
let storeDatabase: RxDatabase;
let syncDatabase: RxDatabase;

// it('should return the default endpoint', () => {
// const mockCollection = new MockRxCollection({ name: 'testCollection' });
// const replicationState = new CollectionReplicationState({
// collection: mockCollection,
// httpClient: {},
// });

// expect(replicationState.getEndpoint()).toBe('testCollection');
// expect(replicationState.endpoint).toBe('testCollection');
// });

// it('should return a custom endpoint from preEndpoint hook', () => {
// const mockCollection = new MockRxCollection({ name: 'testCollection' });
// const customEndpoint = 'customEndpoint';
// const hooks = {
// preEndpoint: jest.fn().mockReturnValue(customEndpoint),
// };
// const replicationState = new CollectionReplicationState({
// collection: mockCollection,
// httpClient: {},
// hooks,
// });
beforeEach(async () => {
storeDatabase = await createStoreDatabase();
syncDatabase = await createSyncDatabase();
});

// expect(replicationState.getEndpoint()).toBe(customEndpoint);
// expect(hooks.preEndpoint).toHaveBeenCalledWith(mockCollection);
// });
afterEach(() => {
jest.clearAllMocks();
storeDatabase.remove();
syncDatabase.remove();
});

describe('fetchRemoteIDs', () => {
it('fetches remote IDs successfully', async () => {
const expectedIds = [1, 2, 3];
httpClientMock.get.mockResolvedValue({ data: expectedIds.map((id) => ({ id })) });

const replicationState = new CollectionReplicationState({
collection: new MockRxCollection({}),
collection: storeDatabase.collections.products,
httpClient: httpClientMock,
});

Expand All @@ -51,7 +36,7 @@ describe('CollectionReplicationState', () => {
httpClientMock.get.mockResolvedValue({ data: null });

const replicationState = new CollectionReplicationState({
collection: new MockRxCollection({}),
collection: storeDatabase.collections.products,
httpClient: httpClientMock,
});

Expand Down
6 changes: 4 additions & 2 deletions tests/helpers/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
ExtractDocumentTypeFromTypedRxJsonSchema,
RxJsonSchema,
} from 'rxdb';
import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode';
// import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode';
import { getRxStorageMemory } from 'rxdb/plugins/storage-memory';

import { logsLiteral } from './schemas/logs';
Expand All @@ -16,7 +16,7 @@ import { variationsLiteral } from './schemas/variations';

import type { RxCollectionCreator, RxCollection, RxDocument } from 'rxdb';

addRxPlugin(RxDBDevModePlugin);
// addRxPlugin(RxDBDevModePlugin);

/**
* Products
Expand Down Expand Up @@ -78,6 +78,7 @@ export async function createStoreDatabase(): Promise<RxDatabase> {
name: 'storedb',
storage: getRxStorageMemory(),
ignoreDuplicate: true,
allowSlowCount: true,
});

const collections = await db.addCollections({ products, variations, logs });
Expand All @@ -93,6 +94,7 @@ export async function createSyncDatabase(): Promise<RxDatabase> {
name: 'syncdb',
storage: getRxStorageMemory(),
ignoreDuplicate: true,
allowSlowCount: true,
});

const collections = await db.addCollections({ products: sync, variations: sync });
Expand Down
37 changes: 19 additions & 18 deletions tests/manager.test.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
import httpClientMock from './__mocks__/http';
import { MockRxDatabase } from './__mocks__/rxdb';
import { Manager } from '../src/manager';
import { createStoreDatabase, createSyncDatabase } from './helpers/db';

import type { RxDatabase } from 'rxdb';

// jest.mock('rxdb');

describe('Manager', () => {
let manager: Manager<RxDatabase>;
let mockDatabase: RxDatabase;

beforeEach(() => {
mockDatabase = new MockRxDatabase() as unknown as RxDatabase;
mockDatabase.addCollections({
testCollection: { schema: {} },
}); // Mock collection
manager = new Manager(mockDatabase, httpClientMock);
let storeDatabase: RxDatabase;
let syncDatabase: RxDatabase;

beforeEach(async () => {
storeDatabase = await createStoreDatabase();
syncDatabase = await createSyncDatabase();
manager = new Manager(storeDatabase, httpClientMock);
});

afterEach(() => {
jest.clearAllMocks();
storeDatabase.remove();
syncDatabase.remove();
});

describe('Query States', () => {
Expand Down Expand Up @@ -59,14 +60,14 @@ describe('Manager', () => {
const queryKeys = ['newQuery'];
manager.registerQuery({
queryKeys,
collectionName: 'testCollection',
collectionName: 'products',
initialParams: {},
});
expect(manager.queries.has(JSON.stringify(queryKeys))).toBe(true);
});

it('should return the specified collection', () => {
expect(manager.getCollection('testCollection')).toBeDefined();
expect(manager.getCollection('products')).toBeDefined();
});

it('should handle non-existent collections', (done) => {
Expand All @@ -83,7 +84,7 @@ describe('Manager', () => {
const queryKeys = ['existingQuery'];
manager.registerQuery({
queryKeys,
collectionName: 'testCollection',
collectionName: 'products',
initialParams: {},
});
expect(manager.getQuery(queryKeys)).toBeDefined();
Expand All @@ -103,7 +104,7 @@ describe('Manager', () => {
const queryKey = ['queryToRemove'];
manager.registerQuery({
queryKey,
collectionName: 'removableCollection',
collectionName: 'products',
initialParams: {},
});
manager.deregisterQuery(queryKey);
Expand All @@ -122,17 +123,17 @@ describe('Manager', () => {
it('should register a collection replication state with a new query', () => {
manager.registerQuery({
queryKeys: ['newQuery'],
collectionName: 'testCollection',
collectionName: 'products',
initialParams: {},
});

expect(manager.replicationStates.has('testCollection')).toBe(true);
expect(manager.replicationStates.has('products')).toBe(true);
});

it('should register a collection replication state with a given endpoint', () => {
manager.registerQuery({
queryKeys: ['newQuery'],
collectionName: 'testCollection',
collectionName: 'products',
initialParams: {},
endpoint: 'testEndpoint',
});
Expand All @@ -143,14 +144,14 @@ describe('Manager', () => {
it('should share a collection replication state between queries with the same endpoint', () => {
manager.registerQuery({
queryKeys: ['newQuery1'],
collectionName: 'testCollection',
collectionName: 'products',
initialParams: {},
endpoint: 'testEndpoint',
});

manager.registerQuery({
queryKeys: ['newQuery2'],
collectionName: 'testCollection',
collectionName: 'products',
initialParams: {},
endpoint: 'testEndpoint',
});
Expand Down
5 changes: 4 additions & 1 deletion tests/provider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import { useQuery } from '../src/use-query';

import type { RxDatabase } from 'rxdb';

// Mock the logger module
jest.mock('@wcpos/utils/src/logger');

describe('QueryProvider', () => {
let storeDatabase: RxDatabase;
let syncDatabase: RxDatabase;
Expand All @@ -19,7 +22,7 @@ describe('QueryProvider', () => {
});

afterEach(() => {
// jest.clearAllMocks();
jest.clearAllMocks();
storeDatabase.remove();
syncDatabase.remove();
cleanup();
Expand Down

0 comments on commit 2b64ae0

Please sign in to comment.