fix(testAdded)

This commit is contained in:
Prakash Maity 2024-08-07 21:50:11 +05:30
parent 0a70f5e10a
commit 392fb9bcca
8 changed files with 98 additions and 5 deletions

18
jest.config.ts Normal file
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);

View File

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

View File

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

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;

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);
});
});

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');
});
});

View File

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