Skip to content

Commit

Permalink
test(SFI-1025): fix unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
shanikantsingh committed Dec 18, 2024
1 parent d5f6baf commit 14d8cf1
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 87 deletions.
47 changes: 26 additions & 21 deletions jest/sfccCartridgeMocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,20 @@ jest.mock(
action: { type: 'mockedAction' },
})),
createRedirectUrl: jest.fn(() => 'mocked_RedirectUrl'),
getService: jest.fn(() => ({
getURL: jest.fn(() => 'mocked_service_url'),
setURL: jest.fn(),
addHeader: jest.fn(),
call: jest.fn(() => ({
status: 'success',
isOk: jest.fn(() => true),
object: {
getText: jest.fn(() =>
'{"data":"mocked api response"}'),

},
}))
}))
}),
{ virtual: true },
);
Expand All @@ -320,6 +334,7 @@ jest.mock(
getCreditCardInstallments: jest.fn(() => true),
getAdyenTokenisationEnabled: jest.fn(() => true),
getAdyenClientKey: jest.fn(() => 'mocked_client_key'),
getAdyenApiKey: jest.fn(() => 'mocked_api_key'),
getGoogleMerchantID: jest.fn(() => 'mocked_google_merchant_id'),
getAdyenCardholderNameEnabled: jest.fn(() => true),
getAdyenPayPalIntent: jest.fn(() => 'mocked_intent'),
Expand Down Expand Up @@ -396,27 +411,6 @@ jest.mock(
{ virtual: true },
);

jest.mock(
'*/cartridge/adyen/utils/lineItemHelper',
() => ({
getDescription: jest.fn((lineItem) => lineItem.productName),
getId: jest.fn((lineItem) => lineItem.productID),
getQuantity: jest.fn((lineItem) => lineItem.quantityValue),
getItemAmount: jest.fn((lineItem) => ({
divide: jest.fn((quantity) => ({
getValue: jest.fn(() => lineItem.adjustedNetPrice / quantity),
})),
})),
getVatAmount: jest.fn((lineItem) => ({
divide: jest.fn((quantity) => ({
getValue: jest.fn(() => lineItem.getAdjustedTax / quantity),
})),
})),
getAllLineItems: jest.fn((lineItem) => lineItem),
}),
{ virtual: true },
);

jest.mock(
'*/cartridge/adyen/utils/paypalHelper',
() => ({
Expand Down Expand Up @@ -479,3 +473,14 @@ jest.mock(
}),
{ virtual: true },
);

jest.mock(
'*/cartridge/adyen/logs/adyenCustomLogs',
() => ({
fatal_log: jest.fn(),
error_log: jest.fn(),
debug_log: jest.fn(),
info_log: jest.fn(),
}),
{ virtual: true },
);
Original file line number Diff line number Diff line change
@@ -1,66 +1,55 @@
const AdyenHelper = require('*/cartridge/adyen/utils/adyenHelper');
const AdyenLogs = require('*/cartridge/adyen/logs/adyenCustomLogs');
const { createCheckoutAttemptId } = require('../analyticsService');

const AdyenHelper = {
getApplicationInfo: jest.fn(),
};

const execute = jest.fn();
const constants = {
SERVICE: {
ADYEN_ANALYTICS: 'ADYEN_ANALYTICS',
},
};

const AdyenLogs = {
error_log: jest.fn(),
};

global.AdyenHelper = AdyenHelper;
global.execute = execute;
global.constants = constants;
global.AdyenLogs = AdyenLogs;

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

it('should return checkoutAttemptId when the execute function is successful', () => {
const mockCheckoutAttemptId = 'test-checkout-attempt-id';
const mockApplicationInfo = { name: 'testApp' };

AdyenHelper.getApplicationInfo.mockReturnValue(mockApplicationInfo);
execute.mockReturnValue({ checkoutAttemptId: mockCheckoutAttemptId });
AdyenHelper.getService.mockImplementationOnce(() => ({
getURL: jest.fn(() => 'mocked_service_url'),
setURL: jest.fn(),
addHeader: jest.fn(),
call: jest.fn(() => ({
status: '200',
isOk: jest.fn(() => true),
object: {
getText: jest.fn(() =>
`{"checkoutAttemptId":"${mockCheckoutAttemptId}"}`),

},
}))
}));

const result = createCheckoutAttemptId();

setTimeout(() => {
expect(AdyenHelper.getApplicationInfo).toHaveBeenCalled();
expect(execute).toHaveBeenCalledWith(constants.SERVICE.ADYEN_ANALYTICS, {
applicationInfo: mockApplicationInfo,
channel: 'Web',
platform: 'Web',
});
expect(result).toEqual({ data: mockCheckoutAttemptId });
}, 0)
expect(result).toEqual({ data: mockCheckoutAttemptId });
});

it('should return an error object and log error when execute throws an error', () => {
const mockError = new Error('Execution failed');
AdyenHelper.getApplicationInfo.mockReturnValue({});
execute.mockImplementation(() => {
throw mockError;
});

AdyenHelper.getService.mockImplementationOnce(() => ({
getURL: jest.fn(() => 'mocked_service_url'),
setURL: jest.fn(),
addHeader: jest.fn(),
call: jest.fn(() => ({
status: 'failed',
isOk: jest.fn(() => false),
getError: jest.fn(() => ({
toString: jest.fn(() => '500')
})),
getStatus: jest.fn(() => 'failed'),
getErrorMessage: jest.fn(() => 'Service error'),
getMsg: jest.fn(() => 'Service error'),
}))
}));
const mockError = new Error('AdyenAnalytics service call error code 500 Error => ResponseStatus: failed | ResponseErrorText: Service error | ResponseText: Service error');
const result = createCheckoutAttemptId();

setTimeout(() => {
expect(AdyenHelper.getApplicationInfo).toHaveBeenCalled();
expect(AdyenLogs.error_log).toHaveBeenCalledWith(
'createCheckoutAttemptId for /analytics call failed:',
mockError
'createCheckoutAttemptId for /analytics call failed:', mockError
);
expect(result).toEqual({ error: true });
}, 0)
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function execute(serviceType, requestObject, checkoutAttemptID = '') {
const callResult = service.call(JSON.stringify(requestObject));
if (!callResult.isOk()) {
throw new Error(
`${serviceType} service call error code${callResult
`${serviceType} service call error code ${callResult
.getError()
.toString()} Error => ResponseStatus: ${callResult.getStatus()} | ResponseErrorText: ${callResult.getErrorMessage()} | ResponseText: ${callResult.getMsg()}`,
);
Expand Down
15 changes: 9 additions & 6 deletions src/cartridges/int_adyen_SFRA/cartridge/adyen/logs/adyenError.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
/* eslint-disable max-classes-per-file */
class AdyenError extends Error {
constructor(message, cause) {
super(message);
this.cause = cause;
this.name = this.constructor.name;
function AdyenError(message) {
this.message = message || 'Something went wrong!';
this.name = this.constructor.name;
const error = new Error(this.message);
this.stack = error.stack;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, AdyenError);
}
}
AdyenError.prototype = Object.create(Error.prototype);
AdyenError.prototype.constructor = AdyenError;

module.exports = {
AdyenError,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ beforeEach(() => {
json: jest.fn(),
setStatusCode: jest.fn(),
};
AdyenLogs.error_log = jest.fn();
});

afterEach(() => {
Expand All @@ -34,8 +33,8 @@ describe('Save Shopper controller', () => {
expect(next).toHaveBeenCalled();
});

xit('Should return response when Save Shopper call is not successful', () => {
res.json = jest.fn(() => {throw new Error('unexpected mock error')});
it('Should return response when Save Shopper call is not successful', () => {
res.json.mockImplementationOnce(() => {throw new Error('unexpected mock error')});
saveShopperData(req, res, next);
expect(AdyenLogs.error_log).toHaveBeenCalledTimes(1);
expect(URLUtils.url).toHaveBeenCalledWith('Error-ErrorCode', 'err', 'general');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ let posAuthorize;
let orderNumber;
let paymentInstrument;
let paymentProcessor;
let Logger;
let AdyenLogs

beforeEach(() => {
AdyenLogs = require('*/cartridge/adyen/logs/adyenCustomLogs');
posAuthorize = require('../posAuthorize');
orderNumber = 'mockedNum';
paymentInstrument = {
paymentTransaction: {},
};
paymentProcessor = 'mockedPaymentProcessor';
Logger = require('dw/system/Logger');
jest.clearAllMocks();
});

Expand All @@ -35,7 +35,7 @@ describe('POS Authorize', () => {
paymentProcessor,
);
expect(authorizeResult).toMatchSnapshot();
expect(Logger.fatal.mock.calls.length).toBe(1);
expect(AdyenLogs.fatal_log).toHaveBeenCalled();
});

it('should return error if createTerminalPayment fails', () => {
Expand All @@ -51,7 +51,7 @@ describe('POS Authorize', () => {
paymentInstrument,
paymentProcessor,
);
expect(Logger.fatal.mock.calls.length).toBe(1);
expect(AdyenLogs.fatal_log).toHaveBeenCalled();
expect(authorizeResult).toMatchSnapshot();
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
/* eslint-disable global-require */
const BasketMgr = require('dw/order/BasketMgr');
const AdyenLogs = require('*/cartridge/adyen/logs/adyenCustomLogs');
const getCheckoutPaymentMethods = require('*/cartridge/adyen/scripts/payments/getCheckoutPaymentMethods');
const getPaymentMethods = require('*/cartridge/adyen/scripts/payments/adyenGetPaymentMethods');
let req;
let res;
let next;
let Logger;

beforeEach(() => {
req = {
locale: {
Expand All @@ -16,7 +17,6 @@ beforeEach(() => {
json: jest.fn(),
};
next = jest.fn();
Logger = require('dw/system/Logger');
});

afterEach(() => {
Expand Down Expand Up @@ -76,14 +76,12 @@ describe('getCheckoutPaymentMethods', () => {
});

it('does not return AdyenPaymentMethods', () => {
getPaymentMethods.getMethods = jest.fn(
new Logger.error('error'),
);
getPaymentMethods.getMethods.mockImplementationOnce(() => {throw new Error('mock error')});
getCheckoutPaymentMethods(req, res, next);
expect(res.json).toHaveBeenCalledWith({
error: true,
});
expect(Logger.fatal.mock.calls.length).toBe(1);
expect(AdyenLogs.fatal_log).toHaveBeenCalled();
expect(next).toHaveBeenCalled();
});
});

0 comments on commit 14d8cf1

Please sign in to comment.