Browse Source

fix(testAdded)

master
Prakash Maity 6 months ago
parent
commit
392fb9bcca
8 changed files with 98 additions and 5 deletions
  1. +18
    -0
      jest.config.ts
  2. +7
    -1
      package.json
  3. +0
    -0
      src/app/(dashboard)/(review)/page.tsx
  4. +1
    -1
      src/app/(dashboard)/products/page.tsx
  5. +7
    -0
      src/services/api/__mocks__/axiosInstance.ts
  6. +33
    -0
      src/services/api/loginApi.test.ts
  7. +29
    -0
      src/services/api/productApi.test.ts
  8. +3
    -3
      src/services/api/productsApi.ts

+ 18
- 0
jest.config.ts View File

@ -0,0 +1,18 @@
import type { Config } from 'jest';
import nextJest from 'next/jest.js';
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
});
// Add any custom config to be passed to Jest
const config: Config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config);

+ 7
- 1
package.json View File

@ -6,7 +6,9 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "next lint",
"test": "jest",
"test:watch": "jest --watch"
},
"dependencies": {
"@emotion/cache": "^11.13.1",
@ -27,12 +29,14 @@
"react-redux": "^9.1.2",
"redux-persist": "^6.0.0",
"sass": "^1.77.8",
"ts-node": "^10.9.2",
"zod": "^3.23.8"
},
"devDependencies": {
"@testing-library/jest-dom": "^6.4.8",
"@testing-library/react": "^16.0.0",
"@testing-library/user-event": "^14.5.2",
"@types/jest": "^29.5.12",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
@ -40,6 +44,8 @@
"eslint": "^8",
"eslint-config-next": "14.2.5",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"ts-jest": "^29.2.4",
"typescript": "^5"
}
}

src/app/(dashboard)/review/page.tsx → src/app/(dashboard)/(review)/page.tsx View File


+ 1
- 1
src/app/(dashboard)/products/page.tsx View File

@ -4,7 +4,7 @@ import React from "react";
import CardHeader from "@mui/material/CardHeader";
import CardContent from "@mui/material/CardContent";
import TitleHeader from "@/components/titleHeader/titleHeader";
import homeServices from "@/services/home.services";
import homeServices from "@/services/api/productsApi";
const HomePage = async () => {
const data = await homeServices.getProducts();


+ 7
- 0
src/services/api/__mocks__/axiosInstance.ts View File

@ -0,0 +1,7 @@
// __mocks__/axiosInstance.ts
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
const mock = new MockAdapter(axios);
export default mock;

+ 33
- 0
src/services/api/loginApi.test.ts View File

@ -0,0 +1,33 @@
import axiosInstance from '../axios/axiosInstance';
import { loginApi } from './loginApi';
jest.mock('../axios/axiosInstance');
describe('login API', () => {
it('should return token on successful login', async () => {
const mockResponse = {
data: {
token: 'fake-token',
},
};
(axiosInstance.post as jest.Mock).mockResolvedValue(mockResponse);
const data = { username: 'emilys', password: 'emilyspass' };
const result = await loginApi(data);
expect(result).toEqual(mockResponse.data);
expect(axiosInstance.post).toHaveBeenCalledWith('/auth/login', data);
});
it('should throw an error on failed login', async () => {
const errorMessage = 'Invalid credentials';
(axiosInstance.post as jest.Mock).mockRejectedValue(
new Error(errorMessage)
);
const data = { username: 'test@example.com', password: 'wrongpassword' };
await expect(loginApi(data)).rejects.toThrow(errorMessage);
expect(axiosInstance.post).toHaveBeenCalledWith('/auth/login', data);
});
});

+ 29
- 0
src/services/api/productApi.test.ts View File

@ -0,0 +1,29 @@
import axios from 'axios';
import homeServices from './productsApi';
jest.mock('axios');
describe('homeServices.getProducts', () => {
afterEach(() => {
jest.clearAllMocks();
});
test('should return data on successful API call', async () => {
const mockData = { products: [{ id: 1, name: 'Product 1' }] };
(axios.get as jest.Mock).mockResolvedValue({ data: mockData });
const result = await homeServices.getProducts();
expect(result).toEqual(mockData);
expect(axios.get).toHaveBeenCalledWith('https://dummyjson.com/products');
});
test('should throw generic error message on non-Axios error', async () => {
(axios.get as jest.Mock).mockRejectedValue(new Error('Non-Axios error'));
await expect(homeServices.getProducts()).rejects.toThrow(
'Something went wrong. Please try again.'
);
expect(axios.get).toHaveBeenCalledWith('https://dummyjson.com/products');
});
});

src/services/home.services.ts → src/services/api/productsApi.ts View File

@ -1,16 +1,16 @@
import axios, { isAxiosError } from "axios";
import axios, { isAxiosError } from 'axios';
/** Product List Home Page */
const homeServices = {
getProducts: async () => {
try {
const res = await axios.get("https://dummyjson.com/products");
const res = await axios.get('https://dummyjson.com/products');
return res.data;
} catch (error: any) {
if (isAxiosError(error)) {
throw new Error(error.response?.data.message);
}
throw new Error("Something went wrong. Please try again.");
throw new Error('Something went wrong. Please try again.');
}
},
};

Loading…
Cancel
Save