Skip to content

Commit

Permalink
Momo changes
Browse files Browse the repository at this point in the history
  • Loading branch information
13XAVI committed Jun 7, 2024
1 parent fe7d511 commit f285b3a
Showing 1 changed file with 52 additions and 77 deletions.
129 changes: 52 additions & 77 deletions src/__test__/Momo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,25 @@ import {
import { getBuyerToken } from './testSetup';
import dbConnection from '../database';
import { Order } from '../database/models/orderEntity';

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

let token: string;
let order: Order;

app.post('/buyer/momoPay', (req, res) => {
MomohandlePayment(req, res);
});

app.post('/buyer/getPaymentStatus/:id', (req, res) => {
checkPaymentStatus(req, res);
});

beforeAll(async () => {
await dbConnection.initialize();
await dbConnection.synchronize(true); // This will drop all tables
token = await getBuyerToken();
// Create a mock order in the database
const orderRepository = dbConnection.getRepository(Order);
order = orderRepository.create({
totalAmount: 100,
Expand All @@ -37,9 +40,16 @@ beforeAll(async () => {
paid: false,
});
await orderRepository.save(order);

jest.mock('../controller/buyerController', () => ({
GenerateApiKey: jest.fn(),
purchaseAccessToken: jest.fn(),
validateMomo: jest.fn(),
checkPaymentStatus: jest.fn(),
requestToPayStatus: jest.fn(),
}));
});

// Type definitions
type Idata = {
access_token: string;
token_type: string;
Expand All @@ -61,7 +71,6 @@ type Ivalidate = {
result: boolean;
};

// Mock data
const mockToken: Idata = {
access_token: 'mockToken',
token_type: 'Bearer',
Expand All @@ -87,23 +96,15 @@ afterEach(() => {
jest.clearAllMocks();
});

const tokenUrl = process.env.TokenUrl as string;
const subscriptionKey = process.env.subscriptionKey as string;
const requesttoPayUrl = process.env.RequestToPayUrl as string;
const targetEnv = process.env.TargetEnv as string;

// Mocking fetch for purchaseAccessToken
global.fetch = jest.fn().mockResolvedValue({
global.fetch = jest.fn().mockImplementation(() => ({
ok: true,
json: () =>
Promise.resolve({
access_token: 'testToken',
token_type: 'Bearer',
expires_in: '3600',
}),
}) as jest.Mock;

// Test suite for Momo functions
json: () => Promise.resolve(mockToken),
}));

describe('Test Momo Functions', () => {
describe('purchaseAccessToken', () => {
const mockAccessToken = 'testToken';
Expand All @@ -112,13 +113,7 @@ describe('Test Momo Functions', () => {
const XRefId = 'test_xref_id';
const targetEnv = 'test_env';

beforeEach(() => {
// Clear all instances and calls to constructor and all methods:
(fetch as jest.Mock).mockClear();
});

it('successfully fetches an access token', async () => {
// Define the mock response for fetch
(fetch as jest.Mock).mockResolvedValue({
ok: true,
json: async () => ({
Expand All @@ -131,10 +126,8 @@ describe('Test Momo Functions', () => {
const accessToken = 'testToken';
(purchaseAccessToken as jest.Mock).mockResolvedValue(mockAccessToken);

// Check the result
expect(accessToken).toBe(mockAccessToken);

// Ensure fetch was called with the correct URL and headers
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch).toHaveBeenCalledWith(tokenUrl, {
method: 'POST',
Expand All @@ -147,19 +140,15 @@ describe('Test Momo Functions', () => {
});

it('handles fetch failure', async () => {
// Define the mock response for fetch to simulate a failed request
(fetch as jest.Mock).mockResolvedValue({
ok: false,
statusText: 'Internal Server Error',
});

// Call the function
const accessToken = await purchaseAccessToken();

// Check the result
expect(accessToken).toBeNull();

// Ensure fetch was called with the correct URL and headers
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch).toHaveBeenCalledWith(tokenUrl, {
method: 'POST',
Expand All @@ -172,18 +161,14 @@ describe('Test Momo Functions', () => {
});

it('handles fetch throwing an error', async () => {
// Define the mock to throw an error
const mockError = new Error('Failed to fetch');
(fetch as jest.Mock).mockRejectedValue(mockError);

// Call the function and handle the error
try {
await purchaseAccessToken();
} catch (error) {
expect(error).toBe(mockError);
}

// Ensure fetch was called with the correct URL and headers
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch).toHaveBeenCalledWith(tokenUrl, {
method: 'POST',
Expand All @@ -209,7 +194,6 @@ describe('Test Momo Functions', () => {
mockStatus.payeeNote
);

// Expecting the entire Response object including ok and json method
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch).toHaveBeenCalledWith(
requesttoPayUrl,
Expand Down Expand Up @@ -253,7 +237,6 @@ describe('Test Momo Functions', () => {
reason: {},
};

// Mock the fetch response
global.fetch = jest.fn().mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve(mockResponse),
Expand Down Expand Up @@ -282,7 +265,6 @@ describe('Test Momo Functions', () => {
const mockMomoAccount = 'mockMomoAccount';
const mockResponse = { result: true };

// Mock the fetch response
global.fetch = jest.fn().mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve(mockResponse),
Expand Down Expand Up @@ -402,54 +384,47 @@ describe('Test Momo Functions', () => {
});

describe('checkPaymentStatus', () => {
it('successfully checks payment status', async () => {
const mockStatus = { status: 'SUCCESSFUL', reason: {} };
(requestToPayStatus as jest.Mock).mockResolvedValue(mockStatus);
it('successfully checks the payment status', async () => {
const mockId = 'mockId';
const mockToken = 'mockToken';
const mockResponse = {
amount: '100',
currency: 'USD',
externalId: 'mockExternalId',
payer: {},
payerMessage: 'Payment for order',
payeeNote: 'Thank you for your purchase',
status: 'Success',
reason: {},
};

const res = await request(app)
.post(`/buyer/getPaymentStatus/${mockOrder.id}`)
.set('Authorization', `Bearer ${token}`)
.send({ requestId: mockRequestId });
global.fetch = jest.fn().mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve(mockResponse),
}) as jest.Mock;

expect(res.status).toBe(200);
expect(res.body).toEqual({
success: true,
message: 'Transaction Done Successfully',
});
const response = await request(app)
.get(`/buyer/getPaymentStatus/${mockId}`)
.set('Authorization', `Bearer ${token}`);

expect(requestToPayStatus).toHaveBeenCalledWith(mockRequestId, mockToken);
expect(requestToPayStatus).toHaveBeenCalledWith(
expect.objectContaining({ paid: true })
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch).toHaveBeenCalledWith(
`${requesttoPayUrl}/${mockId}`,
expect.objectContaining({
method: 'GET',
headers: expect.objectContaining({
'Ocp-Apim-Subscription-Key': subscriptionKey,
Authorization: `Bearer ${mockToken}`,
'X-Target-Environment': targetEnv,
}),
})
);
});

it('returns 404 if order not found', async () => {
const res = await request(app)
.post(`/buyer/getPaymentStatus/999`)
.set('Authorization', `Bearer ${token}`)
.send({ requestId: mockRequestId });

expect(res.status).toBe(404);
expect(res.body).toEqual({ success: false, message: 'Order not found' });
});

it('returns 400 if transaction fails', async () => {
const mockStatus = {
status: 'FAILED',
reason: { message: 'Insufficient funds' },
};
(requestToPayStatus as jest.Mock).mockResolvedValue(mockStatus);

const res = await request(app)
.post(`/buyer/getPaymentStatus/${mockOrder.id}`)
.set('Authorization', `Bearer ${token}`)
.send({ requestId: mockRequestId });

expect(res.status).toBe(400);
expect(res.body).toEqual({
success: false,
message: 'Transaction failed',
reason: mockStatus.reason,
expect(response.status).toBe(200);
expect(response.body).toEqual({
message: 'Payment Status Checked',
status: 'Success',
details: mockResponse,
});
});
});
Expand Down

0 comments on commit f285b3a

Please sign in to comment.