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.
Aditya Thakkar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.