Skip to content

Commit

Permalink
added utils tests
Browse files Browse the repository at this point in the history
  • Loading branch information
nagesh-dixit committed Mar 21, 2024
1 parent e8e4848 commit 93cdd83
Show file tree
Hide file tree
Showing 16 changed files with 382 additions and 33 deletions.
24 changes: 14 additions & 10 deletions free-sample-product-service/src/connector/actions.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { ByProjectKeyRequestBuilder } from '@commercetools/platform-sdk/dist/declarations/src/generated/client/by-project-key-request-builder';
import { readConfiguration } from '../utils/config.utils';
import { Channel } from '@commercetools/platform-sdk';
import { createApiRoot } from '../client/create.client';


const CART_UPDATE_EXTENSION_KEY = 'free-sample-cartUpdateExtension';



export async function createChannelAndInventory(
apiRoot: ByProjectKeyRequestBuilder
): Promise<void> {
export async function createChannelAndInventory(): Promise<void> {

const freeSampleChannelKey:string = readConfiguration().freeSampleChannelKey;
const freeSampleSku:string = readConfiguration().freeSampleSku;
const freeSampleQuantity: number = readConfiguration().freeSampleQuantity;
const freeSampleInventoryKey = "free-sample-" + freeSampleSku;
let channel: Channel;

const apiRoot = createApiRoot();

const {
body: { results: channels },
} = await apiRoot
Expand Down Expand Up @@ -90,9 +91,11 @@ export async function createChannelAndInventory(
}

export async function createCartUpdateExtension(
apiRoot: ByProjectKeyRequestBuilder,
applicationUrl: string
): Promise<void> {

const apiRoot = createApiRoot();

const {
body: { results: extensions },
} = await apiRoot
Expand Down Expand Up @@ -138,15 +141,15 @@ export async function createCartUpdateExtension(
.execute();
}

export async function deleteChannelAndInventory(
apiRoot: ByProjectKeyRequestBuilder
): Promise<void> {
export async function deleteChannelAndInventory(): Promise<void> {

const freeSampleChannelKey:string = readConfiguration().freeSampleChannelKey;
const freeSampleSku:string = readConfiguration().freeSampleSku;
const freeSampleInventoryKey = "free-sample-" + freeSampleSku;
let channel: Channel;

const apiRoot = createApiRoot();

const {
body: { results: channels },
} = await apiRoot
Expand Down Expand Up @@ -196,9 +199,10 @@ export async function deleteChannelAndInventory(
}
}

export async function deleteCartUpdateExtension(
apiRoot: ByProjectKeyRequestBuilder
): Promise<void> {
export async function deleteCartUpdateExtension(): Promise<void> {

const apiRoot = createApiRoot();

const {
body: { results: extensions },
} = await apiRoot
Expand Down
61 changes: 61 additions & 0 deletions free-sample-product-service/src/connector/post-deploy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { assertError } from '../utils/assert.utils';
import * as postDeploy from './post-deploy';
import * as actions from './actions';

jest.mock('../utils/assert.utils', () => ({
assertError: jest.fn(),
assertString: jest.fn(),
}));

jest
.spyOn(actions, 'createChannelAndInventory')
.mockReturnValue(Promise.resolve());

jest
.spyOn(actions, 'createCartUpdateExtension')
.mockReturnValue(Promise.resolve());

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

it('should call postDeploy and handle errors gracefully', async () => {
const mockError = new Error('Test error');
const mockErrorMessage = `Post-deploy failed: ${mockError.message}`;

jest
.spyOn(actions, 'createChannelAndInventory')
.mockRejectedValueOnce(mockError);

jest
.spyOn(actions, 'createCartUpdateExtension')
.mockRejectedValueOnce(mockError);

const writeSpy = jest.spyOn(process.stderr, 'write');

await postDeploy.run();

expect(assertError).toHaveBeenCalledWith(mockError);
expect(writeSpy).toHaveBeenCalledWith(mockErrorMessage);
});

it('should not throw an error when postDeploy succeeds', async () => {
const mockError = new Error('Test error');
jest
.spyOn(postDeploy, 'run')
.mockImplementationOnce(() => Promise.resolve());
const writeSpy = jest.spyOn(process.stderr, 'write');
await postDeploy.run();
jest
.spyOn(actions, 'createChannelAndInventory')
.mockRejectedValueOnce(mockError);

jest
.spyOn(actions, 'createCartUpdateExtension')
.mockRejectedValueOnce(mockError);

expect(assertError).not.toHaveBeenCalled();
expect(writeSpy).not.toHaveBeenCalled();
});
});
10 changes: 4 additions & 6 deletions free-sample-product-service/src/connector/post-deploy.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import dotenv from 'dotenv';
dotenv.config();

import { createApiRoot } from '../client/create.client';
import { assertError, assertString } from '../utils/assert.utils';
import {
// createCustomCartDiscountType,
Expand All @@ -15,13 +14,12 @@ async function postDeploy(properties: Map<string, unknown>): Promise<void> {
const applicationUrl = properties.get(CONNECT_APPLICATION_URL_KEY);

assertString(applicationUrl, CONNECT_APPLICATION_URL_KEY);

const apiRoot = createApiRoot();
await createCartUpdateExtension(apiRoot, applicationUrl);
await createChannelAndInventory(apiRoot);

await createCartUpdateExtension(applicationUrl);
await createChannelAndInventory();
}

async function run(): Promise<void> {
export async function run(): Promise<void> {
try {
const properties = new Map(Object.entries(process.env));
await postDeploy(properties);
Expand Down
59 changes: 59 additions & 0 deletions free-sample-product-service/src/connector/pre-undeploy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { assertError } from '../utils/assert.utils';
import * as preUndeploy from './pre-undeploy';
import * as actions from './actions';

jest.mock('../utils/assert.utils', () => ({
assertError: jest.fn(),
assertString: jest.fn(),
}));

jest
.spyOn(actions, 'deleteChannelAndInventory')
.mockReturnValue(Promise.resolve());

jest
.spyOn(actions, 'deleteCartUpdateExtension')
.mockReturnValue(Promise.resolve());

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

it('should call postDeploy and handle errors gracefully', async () => {
const mockError = new Error('Test error');
const mockErrorMessage = `Pre-undeploy failed: ${mockError.message}`;
jest
.spyOn(actions, 'deleteChannelAndInventory')
.mockRejectedValueOnce(mockError);

jest
.spyOn(actions, 'deleteCartUpdateExtension')
.mockRejectedValueOnce(mockError);
const writeSpy = jest.spyOn(process.stderr, 'write');

await preUndeploy.run();

expect(assertError).toHaveBeenCalledWith(mockError);
expect(writeSpy).toHaveBeenCalledWith(mockErrorMessage);
});

it('should not throw an error when preUndeploy succeeds', async () => {
const mockError = new Error('Test error');
jest
.spyOn(preUndeploy, 'run')
.mockImplementationOnce(() => Promise.resolve());
const writeSpy = jest.spyOn(process.stderr, 'write');
await preUndeploy.run();
jest
.spyOn(actions, 'deleteChannelAndInventory')
.mockRejectedValueOnce(mockError);

jest
.spyOn(actions, 'deleteCartUpdateExtension')
.mockRejectedValueOnce(mockError);

expect(assertError).not.toHaveBeenCalled();
expect(writeSpy).not.toHaveBeenCalled();
});
});
8 changes: 3 additions & 5 deletions free-sample-product-service/src/connector/pre-undeploy.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import dotenv from 'dotenv';
dotenv.config();

import { createApiRoot } from '../client/create.client';
import { assertError } from '../utils/assert.utils';
import { deleteCartUpdateExtension, deleteChannelAndInventory } from './actions';

async function preUndeploy(): Promise<void> {
const apiRoot = createApiRoot();
await deleteChannelAndInventory(apiRoot);
await deleteCartUpdateExtension(apiRoot);
await deleteChannelAndInventory();
await deleteCartUpdateExtension();
}

async function run(): Promise<void> {
export async function run(): Promise<void> {
try {
await preUndeploy();
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,6 @@ const update = async (resource: Resource) => {
}
};



/**
* Handle the cart controller according to the action
*
Expand Down
39 changes: 39 additions & 0 deletions new-category-cleanup-job-app/src/utils/config.utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import CustomError from '../errors/custom.error';
import { readConfiguration } from './config.utils';
import * as validatorHelper from '../validators/helpers.validators';

// Mock .env
const mockEnv = {
CTP_CLIENT_ID: 'mockClientId',
CTP_CLIENT_SECRET: 'mockClientSecret',
CTP_PROJECT_KEY: 'mockProjectKey',
CTP_REGION: 'mockRegion',
NEW_CATEGORY_KEY: 'mockCategoryKey',
};

describe('readConfiguration', () => {
it('should return the correct configuration when env variables are valid', () => {
process.env = mockEnv
const expectedConfig = {
clientId: 'mockClientId',
clientSecret: 'mockClientSecret',
projectKey: 'mockProjectKey',
region: 'mockRegion',
categoryKey: 'mockCategoryKey',
};

// Mock the validation function to return an empty array
jest.spyOn(validatorHelper, 'getValidateMessages').mockReturnValue([]);

const config = readConfiguration();
expect(config).toEqual(expectedConfig);
});

it('should throw a CustomError when env variables are invalid', () => {
process.env = mockEnv
// Mock the validation function to return validation errors
jest.spyOn(validatorHelper, 'getValidateMessages').mockReturnValue(['Invalid variable: CTP_CLIENT_ID']);

expect(() => {readConfiguration();}).toThrow(CustomError);
});
});
7 changes: 7 additions & 0 deletions new-category-cleanup-job-app/src/utils/logger.utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { logger } from "./logger.utils"

describe("logger object", () => {
it("should not throw an error when logger object", () => {
expect(typeof logger).toEqual('object');
});
});
7 changes: 5 additions & 2 deletions new-product-event-app/src/connector/actions.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { ByProjectKeyRequestBuilder } from '@commercetools/platform-sdk/dist/declarations/src/generated/client/by-project-key-request-builder';
import { createApiRoot } from '../client/create.client';

const PRODUCT_PUBLISHED_SUBSCRIPTION_KEY =
'ProductPublishedSubscription';

export async function createProductPublishedSubscription(
apiRoot: ByProjectKeyRequestBuilder,
topicName: string,
projectId: string
): Promise<void> {
const apiRoot = createApiRoot();
const {
body: { results: subscriptions },
} = await apiRoot
Expand Down Expand Up @@ -55,8 +56,10 @@ export async function createProductPublishedSubscription(
}

export async function deleteProductPublishedSubscription(
apiRoot: ByProjectKeyRequestBuilder
): Promise<void> {

const apiRoot = createApiRoot();

const {
body: { results: subscriptions },
} = await apiRoot
Expand Down
50 changes: 50 additions & 0 deletions new-product-event-app/src/connector/post-deploy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { assertError } from '../utils/assert.utils';
import * as postDeploy from './post-deploy';
import * as actions from './actions';

jest.mock('../utils/assert.utils', () => ({
assertError: jest.fn(),
assertString: jest.fn(),
}));

jest
.spyOn(actions, 'createProductPublishedSubscription')
.mockReturnValue(Promise.resolve());

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

it('should call postDeploy and handle errors gracefully', async () => {
const mockError = new Error('Test error');
const mockErrorMessage = `Post-deploy failed: ${mockError.message}`;

jest
.spyOn(actions, 'createProductPublishedSubscription')
.mockRejectedValueOnce(mockError);

const writeSpy = jest.spyOn(process.stderr, 'write');

await postDeploy.run();

expect(assertError).toHaveBeenCalledWith(mockError);
expect(writeSpy).toHaveBeenCalledWith(mockErrorMessage);
});

it('should not throw an error when postDeploy succeeds', async () => {
const mockError = new Error('Test error');
jest
.spyOn(postDeploy, 'run')
.mockImplementationOnce(() => Promise.resolve());

const writeSpy = jest.spyOn(process.stderr, 'write');
await postDeploy.run();
jest
.spyOn(actions, 'createProductPublishedSubscription')
.mockRejectedValueOnce(mockError);

expect(assertError).not.toHaveBeenCalled();
expect(writeSpy).not.toHaveBeenCalled();
});
});
Loading

0 comments on commit 93cdd83

Please sign in to comment.