-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(fix admin dashboard transactions)
- Loading branch information
Showing
7 changed files
with
532 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
import { configureStore } from '@reduxjs/toolkit'; | ||
import axios from 'axios'; | ||
import MockAdapter from 'axios-mock-adapter'; | ||
|
||
import rootReducer from '../../../redux/reducers/rootReducer'; // Adjust the path to your rootReducer | ||
import type { AppDispatch } from '../../../redux/store'; // Import types | ||
import Cookies from 'js-cookie'; | ||
import { AddToCartData } from '../../../types/cartTypes'; | ||
import { addToCart, clearCart, fetchCart, removeFromCart } from '../../../redux/actions/cartAction'; | ||
|
||
describe('cartActions', () => { | ||
let mockAxios: MockAdapter; | ||
let store: ReturnType<typeof configureStore>; | ||
|
||
beforeEach(() => { | ||
mockAxios = new MockAdapter(axios); | ||
store = configureStore({ | ||
reducer: rootReducer, | ||
middleware: (getDefaultMiddleware) => | ||
getDefaultMiddleware({ | ||
serializableCheck: false, | ||
immutableCheck: false | ||
}) | ||
}); | ||
localStorage.setItem('userToken', JSON.stringify({ token: 'test-token' })); | ||
}); | ||
|
||
afterEach(() => { | ||
mockAxios.reset(); | ||
localStorage.clear(); | ||
}); | ||
|
||
it('fetchCart should make the correct API call and handle the response', async () => { | ||
const cartData = { data: { cart: [{ id: 'cart123', totalAmount: 100 }] } }; | ||
mockAxios.onGet(`${import.meta.env.VITE_APP_API_URL}/cart`).reply(200, cartData); | ||
|
||
const result = await (store.dispatch as AppDispatch)(fetchCart()); | ||
|
||
expect(result.type).toBe('cart/fetchCart/fulfilled'); | ||
expect(result.payload).toEqual(cartData); | ||
expect(mockAxios.history.get[0].url).toBe(`${import.meta.env.VITE_APP_API_URL}/cart`); | ||
}); | ||
|
||
it('addToCart should make the correct API call and handle the response', async () => { | ||
const addData: AddToCartData = { productId: 'prod123', quantity: 1 }; | ||
const responseData = { data: { cart: { id: 'cart123' } } }; | ||
mockAxios.onPost(`${import.meta.env.VITE_APP_API_URL}/cart`).reply(200, responseData); | ||
|
||
const result = await (store.dispatch as AppDispatch)(addToCart(addData)); | ||
|
||
expect(result.type).toBe('cart/addToCart/fulfilled'); | ||
expect(result.payload).toEqual(responseData); | ||
expect(mockAxios.history.post[0].url).toBe(`${import.meta.env.VITE_APP_API_URL}/cart`); | ||
expect(Cookies.get('cartId')).toBe('cart123'); | ||
}); | ||
|
||
it('clearCart should make the correct API call and handle the response', async () => { | ||
const responseData = { data: { cart: [] } }; // Mock response should match expected structure | ||
mockAxios.onDelete(`${import.meta.env.VITE_APP_API_URL}/cart`).reply(200, responseData); | ||
|
||
const result = await (store.dispatch as AppDispatch)(clearCart()); | ||
|
||
expect(result.type).toBe('cart/clearCart/fulfilled'); | ||
expect(result.payload).toEqual(responseData); | ||
expect(mockAxios.history.delete[0].url).toBe(`${import.meta.env.VITE_APP_API_URL}/cart`); | ||
}); | ||
|
||
it('removeFromCart should make the correct API call and handle the response', async () => { | ||
const responseData = { data: { cart: [] } }; | ||
const itemId = 'item123'; | ||
mockAxios.onDelete(`${import.meta.env.VITE_APP_API_URL}/cart/${itemId}`).reply(200, responseData); | ||
|
||
const result = await (store.dispatch as AppDispatch)(removeFromCart(itemId)); | ||
|
||
expect(result.type).toBe('cart/removeFromCart/fulfilled'); | ||
expect(result.payload).toEqual(responseData); | ||
expect(mockAxios.history.delete[0].url).toBe(`${import.meta.env.VITE_APP_API_URL}/cart/${itemId}`); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import jwtDecode from 'jwt-decode'; | ||
import { DecodedToken } from '../types/CouponTypes'; | ||
import { decodedToken } from '../services'; | ||
|
||
// Mock jwt-decode module | ||
vi.mock('jwt-decode', () => ({ | ||
default: vi.fn() | ||
})); | ||
|
||
describe('decodedToken', () => { | ||
const originalError = console.error; | ||
|
||
beforeAll(() => { | ||
console.error = vi.fn(); // Mock console.error | ||
}); | ||
|
||
afterAll(() => { | ||
console.error = originalError; // Restore console.error | ||
}); | ||
|
||
afterEach(() => { | ||
localStorage.clear(); | ||
vi.clearAllMocks(); | ||
}); | ||
|
||
it('should return testData if provided', () => { | ||
const testData: DecodedToken = { | ||
id: '123', | ||
email: '[email protected]', | ||
userType: 'admin', | ||
iat: 1615552560, | ||
exp: 1615556160 | ||
}; | ||
const result = decodedToken({ testData }); | ||
expect(result).toEqual(testData); | ||
}); | ||
|
||
it('should return null if no token in localStorage', () => { | ||
const result = decodedToken({}); | ||
expect(result).toBeNull(); | ||
expect(console.error).toHaveBeenCalledWith('No user token found in localStorage'); | ||
}); | ||
|
||
it('should return null if token structure is invalid', () => { | ||
localStorage.setItem('userToken', JSON.stringify({})); | ||
const result = decodedToken({}); | ||
expect(result).toBeNull(); | ||
expect(console.error).toHaveBeenCalledWith('Invalid token structure'); | ||
}); | ||
|
||
it('should return null if there is an error in decoding token', () => { | ||
const mockToken = 'mock.jwt.token'; | ||
(jwtDecode as any).mockImplementation(() => { | ||
throw new Error('Invalid token'); | ||
}); | ||
|
||
localStorage.setItem('userToken', JSON.stringify({ token: mockToken })); | ||
|
||
const result = decodedToken({}); | ||
expect(result).toBeNull(); | ||
expect(console.error).toHaveBeenCalledWith('Error decoding token', expect.any(Error)); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,175 @@ | ||
import React from 'react'; | ||
import { render, screen, waitFor, act } from '@testing-library/react'; | ||
import { describe, it, vi, afterEach } from 'vitest'; | ||
import axios from 'axios'; | ||
import { Provider } from 'react-redux'; | ||
import { MemoryRouter } from 'react-router-dom'; | ||
import store from '../../redux/store'; | ||
import Transactions from '../../pages/Transactions/Transctions'; | ||
|
||
vi.mock('axios'); | ||
const mockedAxios = axios as jest.Mocked<typeof axios>; | ||
|
||
const mockData = { | ||
statistics: { | ||
totalAmount: 5000, | ||
averagePaymentAmount: 1000, | ||
totalCapturedAmount: 4000, | ||
totalPayments: 5, | ||
successfulPayments: 4, | ||
pendingPayments: 1 | ||
}, | ||
payments: [ | ||
{ | ||
id: 'pay_1', | ||
amount: 1000, | ||
created: 1628353200, | ||
status: 'succeeded', | ||
payment_method_types: ['card'] | ||
}, | ||
{ | ||
id: 'pay_2', | ||
amount: 1200, | ||
created: 12628353200, | ||
status: 'pending', | ||
payment_method_types: ['card'] | ||
} | ||
] | ||
}; | ||
|
||
const emptyPaymentsData = { | ||
statistics: { | ||
totalAmount: 0, | ||
averagePaymentAmount: 0, | ||
totalCapturedAmount: 0, | ||
totalPayments: 0, | ||
successfulPayments: 0, | ||
pendingPayments: 0 | ||
}, | ||
payments: [] | ||
}; | ||
|
||
describe('Transactions Component', () => { | ||
afterEach(() => { | ||
vi.clearAllMocks(); | ||
localStorage.clear(); | ||
}); | ||
|
||
it('renders Transactions component without crashing', async () => { | ||
localStorage.setItem('userToken', JSON.stringify({ token: 'mocked-token' })); | ||
mockedAxios.get.mockResolvedValue({ data: mockData }); | ||
|
||
await act(async () => { | ||
render( | ||
<Provider store={store}> | ||
<MemoryRouter> | ||
<Transactions /> | ||
</MemoryRouter> | ||
</Provider> | ||
); | ||
}); | ||
|
||
await waitFor(() => { | ||
expect(screen.getByTestId('transactions')).toBeInTheDocument(); | ||
}); | ||
|
||
expect(screen.getByTestId('totalVendors')).toBeInTheDocument(); | ||
expect(screen.getByTestId('totalVendors')).toHaveTextContent('5,000 Rwf'); | ||
}); | ||
it('displays No Transactions Found when payments array is empty', async () => { | ||
localStorage.setItem('userToken', JSON.stringify({ token: 'mocked-token' })); | ||
mockedAxios.get.mockResolvedValue({ data: emptyPaymentsData }); | ||
|
||
await act(async () => { | ||
render( | ||
<Provider store={store}> | ||
<MemoryRouter> | ||
<Transactions /> | ||
</MemoryRouter> | ||
</Provider> | ||
); | ||
}); | ||
|
||
await waitFor(() => { | ||
expect(screen.getByText('No Transactions Found')).toBeInTheDocument(); | ||
}); | ||
}); | ||
|
||
it('displays "No data available" when no data is fetched', async () => { | ||
mockedAxios.get.mockResolvedValueOnce({ data: null }); | ||
|
||
await act(async () => { | ||
render( | ||
<Provider store={store}> | ||
<MemoryRouter> | ||
<Transactions /> | ||
</MemoryRouter> | ||
</Provider> | ||
); | ||
}); | ||
|
||
await waitFor(() => { | ||
expect(screen.getByText('No data available')).toBeInTheDocument(); | ||
}); | ||
}); | ||
|
||
// it('displays "No Transactions Found" when payments array is empty', async () => { | ||
// localStorage.setItem('userToken', JSON.stringify({ token: 'mocked-token' })); | ||
// mockedAxios.get.mockResolvedValue({ data: mockData }); | ||
|
||
// await act(async () => { | ||
// render( | ||
// <Provider store={store}> | ||
// <MemoryRouter> | ||
// <Transactions /> | ||
// </MemoryRouter> | ||
// </Provider> | ||
// ); | ||
// }); | ||
|
||
// await waitFor(() => { | ||
// expect(screen.getByTestId('transactions')).toBeInTheDocument(); | ||
// }); | ||
|
||
// expect(screen.getByTestId('totalVendors')).toBeInTheDocument(); | ||
// expect(screen.getByTestId('totalVendors')).toHaveTextContent('5,000 Rwf'); | ||
// }); | ||
|
||
// it('displays "No Transactions Found" when payments array is empty', async () => { | ||
// localStorage.setItem('userToken', JSON.stringify({ token: 'mocked-token' })); | ||
// // mockedAxios.get.mockResolvedValue({ data: emptyPaymentsData }); | ||
// mockedAxios.get.mockResolvedValue({ data: mockData }); | ||
// await act(async () => { | ||
// render( | ||
// <Provider store={store}> | ||
// <MemoryRouter> | ||
// <Transactions /> | ||
// </MemoryRouter> | ||
// </Provider> | ||
// ); | ||
// }); | ||
|
||
// await waitFor(() => { | ||
// expect(screen.getByText('No Transactions Found')).toBeInTheDocument(); | ||
// }); | ||
// }); | ||
|
||
it('handles missing token correctly', async () => { | ||
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); | ||
|
||
await act(async () => { | ||
render( | ||
<Provider store={store}> | ||
<MemoryRouter> | ||
<Transactions /> | ||
</MemoryRouter> | ||
</Provider> | ||
); | ||
}); | ||
|
||
expect(consoleSpy).toHaveBeenCalledWith('Token not found'); | ||
expect(screen.getByText('No data available')).toBeInTheDocument(); | ||
|
||
consoleSpy.mockRestore(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.