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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: Add tests for QueryEngine and utils for query package. #55

Draft
wants to merge 2 commits into
base: develop
Choose a base branch
from
Draft
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
48 changes: 48 additions & 0 deletions packages/query/src/query-engine/tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { QueryEngine } from '@/query-engine';
import { getConfig, getGraphqlUrl } from '@snapwp/core/config';
import { ApolloClient, InMemoryCache } from '@apollo/client';

jest.mock( '@snapwp/core/config', () => ( {
getConfig: jest.fn(),
getGraphqlUrl: jest.fn(),
} ) );

jest.mock( '@apollo/client', () => ( {
ApolloClient: jest.fn(),
InMemoryCache: jest.fn(),
} ) );

describe( 'QueryEngine', () => {
const validConfig = {
homeUrl: 'https://home.example.com',
};
const graphqlUrl = 'https://graphql.example.com';

beforeEach( () => {
jest.clearAllMocks();
( getConfig as jest.Mock ).mockReturnValue( validConfig );
( getGraphqlUrl as jest.Mock ).mockReturnValue( graphqlUrl );
( InMemoryCache as jest.Mock ).mockImplementation( () => ( {
writeQuery: jest.fn(),
readQuery: jest.fn(),
} ) );
} );

it( 'should initialize the QueryEngine correctly', () => {
QueryEngine.initialize();

expect( getGraphqlUrl ).toHaveBeenCalled();
expect( getConfig ).toHaveBeenCalled();
expect( ( QueryEngine as any ).graphqlEndpoint ).toBe( graphqlUrl );
expect( ( QueryEngine as any ).homeUrl ).toBe( validConfig.homeUrl );
expect( ( QueryEngine as any ).apolloClient ).toBeInstanceOf(
ApolloClient
);
} );

it( 'should be a singleton', () => {
const instance1 = QueryEngine.getInstance();
const instance2 = QueryEngine.getInstance();
expect( instance1 ).toBe( instance2 );
} );
} );
10 changes: 9 additions & 1 deletion packages/query/src/utils/parse-global-styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,18 @@ export default function parseQueryResult(
): GlobalHeadProps {
if ( queryData.errors?.length ) {
queryData.errors?.forEach( ( error ) => {
Logger.error( `Error fetching global styles: ${ error }` );
Logger.error(
`Error fetching global styles: ${ error?.message }`,
error
);
} );
}

// Check if globalStyles is null.
if ( queryData.data.globalStyles === null ) {
throw new GlobalStylesParseError( `Error fetching global styles.` );
}

if ( ! queryData.data && queryData.errors?.length ) {
throw new GlobalStylesParseError( `Error fetching global styles.` );
}
Expand Down
7 changes: 7 additions & 0 deletions packages/query/src/utils/parse-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ export default function parseQueryResult(
} );
}

// Check if data.templateByUri is null
if ( ! queryData.data.templateByUri ) {
throw new TemplateParseError(
`Error fetching template data for uri: ${ uri }`
);
}

if ( ! queryData.data && queryData.errors?.length ) {
throw new TemplateParseError(
`Error fetching template data for uri: ${ uri }`
Expand Down
101 changes: 101 additions & 0 deletions packages/query/src/utils/tests/parse-global-styles.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { ApolloQueryResult } from '@apollo/client';
import { Logger, GlobalStylesParseError } from '@snapwp/core';
import parseQueryResult from '../parse-global-styles';
import { GetGlobalStylesQuery } from '@graphqlTypes/graphql';

jest.mock( '@snapwp/core', () => ( {
...jest.requireActual( '@snapwp/core' ),
Logger: {
error: jest.fn(),
},
} ) );

describe( 'parseQueryResult', () => {
beforeEach( () => {
jest.clearAllMocks();
} );

it( 'should parse valid query data correctly', () => {
const queryData: ApolloQueryResult< GetGlobalStylesQuery > = {
data: {
globalStyles: {
customCss: 'body { color: red; }',
stylesheet: 'styles.css',
renderedFontFaces: '@font-face { font-family: "MyFont"; }',
},
},
errors: [],
loading: false,
networkStatus: 7,
};

const result = parseQueryResult( queryData );

expect( result ).toEqual( {
customCss: 'body { color: red; }',
globalStylesheet: 'styles.css',
renderedFontFaces: '@font-face { font-family: "MyFont"; }',
} );
} );

it( 'should log errors and still parse data if both data and errors exist', () => {
const queryData: ApolloQueryResult< GetGlobalStylesQuery > = {
data: {
globalStyles: {
customCss: 'body { color: blue; }',
stylesheet: 'theme.css',
renderedFontFaces:
'@font-face { font-family: "OtherFont"; }',
},
},
errors: [ { message: 'Sample error message' } ],
loading: false,
networkStatus: 7,
};

const result = parseQueryResult( queryData );

expect( Logger.error ).toHaveBeenCalledWith(
'Error fetching global styles: Sample error message',
{ message: 'Sample error message' }
);
expect( result ).toEqual( {
customCss: 'body { color: blue; }',
globalStylesheet: 'theme.css',
renderedFontFaces: '@font-face { font-family: "OtherFont"; }',
} );
} );

it( 'should throw an error if `data.globalStyles` is null and errors exist', () => {
const queryData: ApolloQueryResult< GetGlobalStylesQuery > = {
data: { globalStyles: null },
errors: [ { message: 'Critical error occurred' } ],
loading: false,
networkStatus: 7,
};

expect( () => parseQueryResult( queryData ) ).toThrow(
GlobalStylesParseError
);
expect( Logger.error ).toHaveBeenCalledWith(
'Error fetching global styles: Critical error occurred',
{ message: 'Critical error occurred' }
);
} );

it( 'should throw an error if `data.globalStyles` is null and no errors exist', () => {
const queryData: ApolloQueryResult< GetGlobalStylesQuery > = {
data: { globalStyles: null },
// @ts-ignore
// data: null,
errors: [],
loading: false,
networkStatus: 7,
};

expect( () => parseQueryResult( queryData ) ).toThrow(
GlobalStylesParseError
);
expect( Logger.error ).not.toHaveBeenCalled();
} );
} );
112 changes: 112 additions & 0 deletions packages/query/src/utils/tests/parse-template.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { ApolloQueryResult } from '@apollo/client';
import {
BlockData,
Logger,
TemplateParseError,
TemplateData,
} from '@snapwp/core';
import parseQueryResult from '@/utils/parse-template';
import { GetCurrentTemplateQuery } from '@graphqlTypes/graphql';

jest.mock( '@snapwp/core', () => ( {
...jest.requireActual( '@snapwp/core' ),
Logger: {
error: jest.fn(),
},
} ) );

describe( 'parseQueryResult', () => {
const wordpressUrl = 'https://test.com';
const uri = '/sample-template';

beforeEach( () => {
jest.clearAllMocks();
} );

it( 'should parse valid query data correctly', () => {
const queryData: ApolloQueryResult< GetCurrentTemplateQuery > = {
data: {
templateByUri: {
bodyClasses: [ 'class1', 'class2' ],
enqueuedScripts: {
nodes: [
{
id: '122',
src: '/script.js',
handle: 'test-script',
},
{
id: '123',
src: 'https://cdn.com/script.js',
handle: 'cdn-script',
},
],
},
enqueuedStylesheets: {
nodes: [
{
src: '/style.css',
handle: 'test-style',
before: [ 'before-content' ],
after: [ 'after-content' ],
},
],
},
editorBlocks: [
{
type: 'core/paragraph',
renderedHtml: '<p>Text</p>',
},
],
},
},
errors: [],
loading: false,
networkStatus: 7,
};

const result = parseQueryResult( queryData, wordpressUrl, uri );

expect( result ).toEqual< TemplateData >( {
stylesheets: [
{
src: 'https://test.com/style.css',
handle: 'test-style',
before: 'before-content',
after: 'after-content',
},
],
editorBlocks: [
{
type: 'core/paragraph',
renderedHtml: '<p>Text</p>',
},
],
scriptModules: undefined,
scripts: [
{ src: 'https://test.com/script.js', handle: 'test-script' },
{ src: 'https://cdn.com/script.js', handle: 'cdn-script' },
],
bodyClasses: [ 'class1', 'class2' ],
} );
} );

it( 'should throw an error if `data` is null and errors exist', () => {
const queryData: ApolloQueryResult< GetCurrentTemplateQuery > = {
data: { templateByUri: null },
errors: [ { message: 'Critical error occurred' } ],
loading: false,
networkStatus: 7,
};

expect( () =>
parseQueryResult( queryData, wordpressUrl, uri )
).toThrow( TemplateParseError );

expect( Logger.error ).toHaveBeenCalledWith(
'Error fetching template data: Critical error occurred.',
'(Please refer to our FAQs for steps to debug and fix)',
{ message: 'Critical error occurred' }
);
} );
} );