Jest Mock Error :- Here test cases are not working fine

So here I have written test cases in jest for my project. When I run all the test cases together some test case fails where same mocks are being shared but when i run together it works fine.

This is the index.tx :-

import './admin-management/admin.management.test';
import './admin-auth/user.auth.test';
import './admin-warehouse/warehouse.test';
import './dashboard/dashboard.test';
import './admin-orders-management.ts/orders.test';
import './item-info-management/item.info.test';
import './notifications/notifications.test';
import './associate-management/associate.management.test';

Here the example of the test case :-

describe('GET RECENT ORDERS', () => {
        beforeEach(() => {
            jest.clearAllMocks();
        });

        afterEach(() => {
            jest.clearAllMocks();
        });

        test('should return 403 if authorization token is required', async () => {
            const response = await request(app)
                .post('/api/v1/admin/recent/orders')
                .send({});

            expect(response.statusCode).toBe(403);
            expect(response.body.message).toBe(
                'A token is required for authentication'
            );
        });

        test('should return 401 if token is expired or invalid', async () => {
            (jwt.sign as jest.Mock).mockReturnValue({
                token: userToken,
            });
            (jwt.verify as jest.Mock).mockImplementation(() => {
                throw new Error('Token is expired or invalid');
            });
            const response = await request(app)
                .post('/api/v1/admin/recent/orders')
                .set('Authorization', `Bearer${userToken}`)
                .send({});
            expect(response.statusCode).toBe(401);
            expect(response.body.message).toBe('Token is expired or invalid');
        });

        test('should return 401 if unauthorized access', async () => {
            (jwt.sign as jest.Mock).mockReturnValue({
                token: userToken,
            });
            (jwt.verify as jest.Mock).mockReturnValue({
                id: userId,
            });
            (User.findById as jest.Mock).mockReturnValue(null);
            const response = await request(app)
                .post('/api/v1/admin/recent/orders')
                .set('Authorization', `Bearer${userToken}`)
                .send({});
            expect(response.statusCode).toBe(401);
            expect(response.body.message).toBe('Unauthorized access');
        });

        test('should return 200 if recent orders are accessed successfully', async () => {
            const mockOrders = [
                {
                    projectName: 'Project A',
                    customerId: { userName: 'User A' },
                    warehouseId: { warehouseName: 'Warehouse A' },
                    dCreated: -1,
                },
            ];

            (jwt.sign as jest.Mock).mockReturnValue({
                token: userToken,
            });

            (jwt.verify as jest.Mock).mockReturnValue({
                id: userId,
            });

            (User.findById as jest.Mock).mockReturnValue({});
            (Order.countDocuments as jest.Mock).mockResolvedValueOnce(2);
            (Order.find as jest.Mock).mockReturnValue({
                populate: jest.fn().mockReturnThis(),
                sort: jest.fn().mockReturnThis(),
                lean: jest.fn().mockResolvedValue(mockOrders),
                select: jest.fn().mockReturnThis(),
                skip: jest.fn().mockReturnThis(),
                limit: jest.fn().mockReturnThis(),
            });

            const response = await request(app)
                .post('/api/v1/admin/recent/orders')
                .set('Authorization', `Bearer${userToken}`)
                .send({
                    draw: 1,
                });

            console.log(
                'This type of response i am getting from recent orders',
                response.body
            );

            expect(response.statusCode).toBe(200);
            expect(response.body.message).toBe('Orders fetched successfully');
            expect(response.body.data).toHaveLength(1);
        });
    });

I do reset mocks in all the test cases and individually it runs perfect but if i run all some test fails.

this is my config file :-

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "lib": ["es2015", "dom"],
        "sourceMap": true,                       
        "outDir": "./build",
    
        "strict": true,
        "strictPropertyInitialization": false,
    
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
    
        "moduleResolution": "node",
        "types": ["node", "jest"],
        "esModuleInterop": true,
        "inlineSources": false,
        "resolveJsonModule": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "skipLibCheck": true,
    },
    "include": ["src"],
  }
  
  

this my test module in package.json :-

{
  "name": "sfl-backend-nodejs",
  "version": "0.0.1",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "rimraf build && tsc && env-cmd -f .env.development pm2 start ./build/index.js --name app",
    "stop": "pm2 stop ./build/index.js",
    "dev": "env-cmd -f .env.development nodemon ./src/index.ts",
    "test-watch": "jest --watchAll --no-cache",
    "test": "env-cmd -f .env.development jest --forceExit"
  },
  "jest": {
    "preset": "ts-jest",
    "testTimeout": 30000,
    "testEnvironment": "node",
    "setupFilesAfterEnv": [
      "./src/test/index.ts"
    ],
    "testMatch": [
      "<rootDir>/src/test/index.ts"
    ],
    "moduleDirectories": [
      "node_modules",
      "src"
    ],
    "collectCoverage": true,
    "coverageReporters": [
      "json",
      "html"
    ]
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@aws-sdk/lib-storage": "^3.540.0",
    "@firebase/auth": "^1.6.2",
    "bcrypt": "^5.1.1",
    "body-parser": "^1.20.2",
    "chai": "^5.1.0",
    "cors": "^2.8.5",
    "crypto": "^1.0.1",
    "csv-parse": "^5.5.6",
    "csvtojson": "^2.0.10",
    "ejs": "^3.1.9",
    "express": "^4.19.2",
    "express-validator": "^7.0.1",
    "firebase-admin": "^11.5.0",
    "generate-password": "^1.7.1",
    "jimp": "^0.22.12",
    "jsonwebtoken": "^9.0.2",
    "mocha": "^10.4.0",
    "mongodb": "^6.5.0",
    "mongoose": "^8.2.3",
    "multer": "^1.4.5-lts.1",
    "nodemailer": "^6.9.13",
    "sinon": "^17.0.1",
    "socket.io": "^4.7.5",
    "validator": "^13.11.0"
  },
  "devDependencies": {
    "@types/bcrypt": "^5.0.2",
    "@types/chai": "^4.3.14",
    "@types/cors": "^2.8.13",
    "@types/ejs": "^3.1.5",
    "@types/jest": "^29.4.0",
    "@types/mocha": "^10.0.6",
    "@types/multer": "^1.4.11",
    "@types/node": "^18.14.5",
    "@types/nodemailer": "^6.4.14",
    "@types/sinon": "^17.0.3",
    "@types/supertest": "^2.0.12",
    "@types/validator": "^13.11.9",
    "dotenv": "^16.0.3",
    "env-cmd": "^10.1.0",
    "jest": "^29.4.3",
    "nodemon": "^2.0.20",
    "supertest": "^6.3.4",
    "ts-jest": "^29.0.5",
    "ts-node": "^10.9.2",
    "typescript": "^4.9.5"
  }
}

I try everything to clear mocks but in some tests the response has been changed when run together.
I am expecting all the tests run together.

New contributor

Aditya Thakkar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật