Skip to content

Commit

Permalink
Merge pull request #36 from flotiq/20758-tests-and-cli
Browse files Browse the repository at this point in the history
20758 tests and cli
  • Loading branch information
CiotkaCierpienia authored Jan 19, 2022
2 parents 13a0ac5 + c01ce4e commit 6fd7c85
Show file tree
Hide file tree
Showing 5 changed files with 21,476 additions and 2,029 deletions.
95 changes: 71 additions & 24 deletions __tests__/default-usage.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jest.mock('node-fetch');
const fetch = require('node-fetch');
const {Response} = jest.requireActual('node-fetch');

const {sourceNodes} = require('../gatsby-node');
const {sourceNodes, onPluginInit} = require('../gatsby-node');

function createObjectWithMethods(functionNames) {
return functionNames.reduce((acc, name) => {
Expand All @@ -24,6 +24,53 @@ function createObjectWithMethods(functionNames) {
beforeEach(() => {
resetAllWhenMocks()
})
describe('onPluginInit', () => {
test('Success Init plugin', async () => {
const gatsbyFunctions = {
actions: createObjectWithMethods(['createNode']),
reporter: createObjectWithMethods(['panic']),
schema: createObjectWithMethods(['buildObjectType'])
};
const options = {
baseUrl: "https://api.flotiq.com",
authToken: 'qweasdzxcrtyfghvbnqweasdzxcrtyfg',
contentTypeDefinitions: [],
};

const expectedHeaders = expect.objectContaining({
headers: expect.objectContaining({
'X-AUTH-TOKEN': options.authToken
})
})
when(fetch)
.expectCalledWith(
expect.stringContaining(`${options.baseUrl}/api/v1/internal/contenttype`),
expectedHeaders
)
.mockReturnValueOnce(Promise.resolve(new Response(`{"data": [${CTD1_STR}]}`)))

await onPluginInit(gatsbyFunctions, options);

verifyAllWhenMocksCalled()
});

test('Failed init plugin when no api key', async () => {
const reporter = createObjectWithMethods(['panic']);
const gatsbyFunctions = {
actions: createObjectWithMethods(['createNode']),
reporter: reporter,
schema: createObjectWithMethods(['buildObjectType'])
};
const options = {
authToken: '',
contentTypeDefinitions: [],
};

await onPluginInit(gatsbyFunctions, options);

expect(reporter.panic).toHaveBeenCalledTimes(1);
});
});

describe('sourceNodes', () => {
test('Downloads the data from scratch', async () => {
Expand All @@ -37,7 +84,8 @@ describe('sourceNodes', () => {
};
const baseUrl = 'https://api.flotiq.com';
const options = {
authToken: 'qweasdzxcrtyfghvbnqweasdzxcrtyfg'
authToken: 'qweasdzxcrtyfghvbnqweasdzxcrtyfg',
contentTypeDefinitions: [CTD1]
};

const expectedHeaders = expect.objectContaining({
Expand All @@ -47,18 +95,17 @@ describe('sourceNodes', () => {
})

when(fetch)
.expectCalledWith(expect.stringContaining(`${baseUrl}/api/v1/internal/contenttype`), expectedHeaders)
.mockReturnValueOnce(Promise.resolve(new Response(`{"data": [${CTD1_STR}]}`)))

when(fetch)
.expectCalledWith(expect.stringContaining(`${baseUrl}/api/v1/content/${CTD1.name}`), expectedHeaders)
.mockReturnValueOnce(Promise.resolve(new Response(`{"data": [${CTD1_OBJECT1_STR}]}`)))
.expectCalledWith(
expect.stringContaining(`${baseUrl}/api/v1/content/Type-1-name?limit=1000&page=1`),
expectedHeaders
)
.mockReturnValueOnce(Promise.resolve(new Response(`{"data": [${CTD1_OBJECT1_STR}]}`)));

await sourceNodes(gatsbyFunctions, options)

verifyAllWhenMocksCalled()
expect(gatsbyFunctions.schema.buildObjectType).toHaveBeenCalledTimes(1)
expect(actions.createNode).toHaveBeenCalledWith(expect.objectContaining(CTD1_OBJECT1_DATA))
expect(actions.createNode).toHaveBeenCalledTimes(1);
expect(actions.setPluginStatus).toHaveBeenCalledTimes(1);
});

describe('When launched second time', () => {
Expand All @@ -81,9 +128,11 @@ describe('sourceNodes', () => {
reporter: createObjectWithMethods(['info','panic','warn']),
schema: createObjectWithMethods(['buildObjectType'])
};

const baseUrl = 'https://api.flotiq.com';
const options = {
authToken: 'qweasdzxcrtyfghvbnqweasdzxcrtyfg'
authToken: 'qweasdzxcrtyfghvbnqweasdzxcrtyfg',
contentTypeDefinitions: [CTD1],
};

const expectedHeaders = expect.objectContaining({
Expand All @@ -92,10 +141,6 @@ describe('sourceNodes', () => {
})
})

when(fetch)
.calledWith(expect.stringContaining(`${baseUrl}/api/v1/internal/contenttype`), expectedHeaders)
.mockReturnValueOnce(Promise.resolve(new Response(`{"data": [${CTD1_STR}]}`)))

when(fetch)
.calledWith(expect.stringMatching(`${baseUrl}/api/v1/content/${CTD1.name}.*updatedAt.*${encodeURIComponent(LAST_UPDATE)}`), expectedHeaders)
.mockReturnValueOnce(Promise.resolve(new Response(`{"data": []}`)))
Expand All @@ -113,6 +158,7 @@ describe('sourceNodes', () => {
test('Updates only new data', async () => {
const actions = createObjectWithMethods(['createNode','setPluginStatus','touchNode','deleteNode']);
const LAST_UPDATE = '2020-01-01T00:00:00Z';

const gatsbyFunctions = {
actions,
store: {getState: jest.fn(_ => {return { status: {plugins: {
Expand All @@ -133,7 +179,8 @@ describe('sourceNodes', () => {
};
const baseUrl = 'https://api.flotiq.com';
const options = {
authToken: 'qweasdzxcrtyfghvbnqweasdzxcrtyfg'
authToken: 'qweasdzxcrtyfghvbnqweasdzxcrtyfg',
contentTypeDefinitions: [CTD1],
};

const expectedHeaders = expect.objectContaining({
Expand All @@ -143,16 +190,16 @@ describe('sourceNodes', () => {
})

when(fetch)
.calledWith(expect.stringContaining(`${baseUrl}/api/v1/internal/contenttype`), expectedHeaders)
.mockReturnValueOnce(Promise.resolve(new Response(`{"data": [${CTD1_STR}]}`)))
.calledWith(
expect.stringMatching(`${baseUrl}/api/v1/content/${CTD1.name}.*updatedAt.*${encodeURIComponent(LAST_UPDATE)}`),
expectedHeaders
).mockReturnValueOnce(Promise.resolve(new Response(`{"data": [${CTD1_OBJECT1_STR}]}`)))

when(fetch)
.calledWith(expect.stringMatching(`${baseUrl}/api/v1/content/${CTD1.name}.*updatedAt.*${encodeURIComponent(LAST_UPDATE)}`), expectedHeaders)
.mockReturnValueOnce(Promise.resolve(new Response(`{"data": [${CTD1_OBJECT1_STR}]}`)))

when(fetch)
.calledWith(expect.stringMatching(`${baseUrl}/api/v1/content/${CTD1.name}/removed\\?deletedAfter=${encodeURIComponent(LAST_UPDATE)}`), expectedHeaders)
.mockReturnValueOnce(Promise.resolve(new Response(`[]`)))
.calledWith(
expect.stringMatching(`${baseUrl}/api/v1/content/${CTD1.name}/removed\\?deletedAfter=${encodeURIComponent(LAST_UPDATE)}`),
expectedHeaders
).mockReturnValueOnce(Promise.resolve(new Response(`[]`)))

await sourceNodes(gatsbyFunctions, options)

Expand Down
22 changes: 12 additions & 10 deletions gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ exports.onPluginInit = async ({actions, schema, reporter}, options) => {
downloadMediaFileGlobal = downloadMediaFile;
apiUrl = baseUrl;
globalSchema = schema;
contentTypeDefsData = await getContentTypes(options, apiUrl);
if (authToken) {
contentTypeDefsData = await getContentTypes(options, apiUrl);
}

if (!apiUrl) {
reporter.panic('FLOTIQ: You must specify API url ' +
Expand Down Expand Up @@ -78,7 +80,7 @@ exports.sourceNodes = async (gatsbyFunctions, options) => {

if (lastUpdate && lastUpdate.updated_at) {
removed = await getDeletedObjects(gatsbyFunctions, options, lastUpdate.updated_at, contentTypeDefsData, apiUrl, async (ctd, id) => {
let node = existingNodes.find(n => n.id === ctd.name + '_' + id);
let node = existingNodes.find(n => n.id === `${ctd.name}_${id}`);
return await deleteNode({node});
});
}
Expand All @@ -89,7 +91,7 @@ exports.sourceNodes = async (gatsbyFunctions, options) => {
// custom
flotiqInternal: datum.internal,
// required
id: ctd.name === '_media' ? datum.id : ctd.name + '_' + datum.id,
id: ctd.name === '_media' ? datum.id : `${ctd.name}_${datum.id}`,
parent: null,
children: [],
internal: {
Expand All @@ -100,17 +102,17 @@ exports.sourceNodes = async (gatsbyFunctions, options) => {
})

if (changed) {
reporter.info('Updated entries ' + changed);
reporter.info(`Updated entries ${changed}`);
}
if (removed) {
reporter.info('Removed entries ' + removed);
reporter.info(`Removed entries ${removed}`);
}
setPluginStatus({
'updated_at':
(new Date()).toISOString().replace(/T/, ' ').replace(/\..+/, '')
});
} catch (e) {
reporter.panic('FLOTIQ: ' + e.message)
reporter.panic(`FLOTIQ: ${e.message}`)
}

return {};
Expand Down Expand Up @@ -217,7 +219,7 @@ exports.createResolvers = ({
createNode,
createNodeId,
reporter,
ext: '.' + source.extension
ext: `.${source.extension}`
});
}
}
Expand Down Expand Up @@ -297,7 +299,7 @@ const getType = (propertyConfig, required, property, ctdName) => {
let typeNonCapitalize = (propertyConfig.validation.relationContenttype !== '_media' ?
propertyConfig.validation.relationContenttype : '_media');
return {
type: '[' + type + ']',
type: `[${type}]`,
resolve: async (source, args, context, info) => {
if (source[property]) {
let nodes = await Promise.all(source[property].map(async (prop) => {
Expand All @@ -320,7 +322,7 @@ const getType = (propertyConfig, required, property, ctdName) => {
// custom
flotiqInternal: json.internal,
// required
id: typeNonCapitalize === '_media' ? json.id : typeNonCapitalize + '_' + json.id,
id: typeNonCapitalize === '_media' ? json.id : `${typeNonCapitalize}_${json.id}`,
parent: null,
children: [],
internal: {
Expand All @@ -346,7 +348,7 @@ const getType = (propertyConfig, required, property, ctdName) => {
}
};
case 'object':
return '[' + capitalize(property) + ctdName + ']';
return `[${capitalize(property)}${ctdName}]`;
case 'block':
return 'FlotiqBlock'
}
Expand Down
Loading

0 comments on commit 6fd7c85

Please sign in to comment.